Difference between toString and Java serialization

I used Jersey to create a JAR-RS web service that responds with JSON formatted data.

When an annotated request comes in @Path

, the method hijacks the request process and returns something.

For example, I created a JSONArray

named object JSONArray

in the method that handles the request. I can use return jsonArray.toString();

to get a string and send it back. I can also use return jsonArray

JAXB (annotation @XmlRootElement

in the JSONArray class and @Produces({ MediaType.APPLICATION_JSON})

in the method) to automatically serialize the object in JSON format.

I would like to know what is the difference between manually posting a String and automatic serialization using annotations. (Performance?)

+3


source to share


1 answer


No, there is no difference in output. The main difference is that it return jsonArray

can be considered more readable (especially to other programmers) and return jsonArray.toString()

more explicit. The problem with the former is that things are more obscure, since someone reading your code needs to figure out that something that receives an object jsonArray

is silently serializing it.

Another difference between the approaches is that letting the framework ensure that possible updates to the framework are reflected in how things get serialized. The method toString()

was not originally intended to provide a serialized representation of an object that can later be used to return an object, but simply provides a textual (even incomplete) representation of the object.

If the class you are using does not provide serialization, or if the provided serialization does not generate JSON (or whatever format you want) correctly, you can always create your own serialization. Wrap the object inside one of the class you define and make that class serializable. Then follow these steps:



private void writeObject (ObjectOutputStream out) throws an IOException; private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException;

And yes, they must be private. See more here: Discover the secrets of the Java Serialization API

+2


source







All Articles