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
, the method hijacks the request process and returns something.
For example, I created a
in the method that handles the request. I can use
to get a string and send it back. I can also use
in the JSONArray class and
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?)
source to share
No, there is no difference in output. The main difference is that it
can be considered more readable (especially to other programmers) and
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
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
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
source to share