JSONObject class of package org.codehaus.groovy.grails.web.json does not implement Serializable.
I want to make this object serializable as I am using session replication among application servers and JSONObject gets saved in session.
I have two options to achieve this:
Subclass JSONObjects that implements Serializable.
use toString() method on JSONObject object while saving this object in session.
Can anyone please suggest which one of two options should I use and what is the reason?
I think the toString method is what's intended to be used here. That method already returns the JSON text of the object, which is suitable for transmitting or storing.
You don't need to serialize JSON, it is already in a store-able form(sort of the whole point of JSON). Grails has JSON parsers and "slurpers" all ready to use for you. So just store the JSON data as a string and use a parser on it to read it back out of the file.
Related
Currently I am working in a project where we are using restful services and jdbc connection. We can handle request response either by jsonObject or with a POJO class. I am confused between these. which one to use and why?
Yes you can read response by using either but if you use jsonObject it will give you an immutable JSON object value. Now it all comes down to your requirement if you have a requirement where you don't need to change any value then you can directly read the response and send it to where ever you want but if you are doing any modification then you need POJO with getter and setter methods.
Similarly in case of creating a request you can use below code:
JsonObject object = Json.createObjectBuilder().build();
but then you end up creating all the nodes and child which is ok for small request but it there are more fields in request then using POJO is a good idea.
POJO:
Its a simple blue print that defines the properties with getter and setter.
jsonObject:
This is a simple data interchangeable format used for client-server interaction
You can use both. If you are receiving Json request or response as string you can convert it to a Json object. Then you can map that fields into POJO class and use them through the POJO class to build your code logic.
I used Jersey to create a JAR-RS Web Service that responds with JSON formatted data.
When a request arrives, with the #Path annotation, a method captures the request processes it and return something.
For example, I created a JSONArray object called 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 and JAXB(the annoation #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 sending back a String and automatic serialization by using annotations.(Performance?)
No, there is no output difference. The main difference is that return jsonArray can be considered to be more readable (especially for other programmers), while return jsonArray.toString() is more explicit. The problem with the former is that things are more obscure as someone reading your code needs to understand that something that gets the jsonArray object silently serializes it.
Another difference between approaches is that letting the framework do it guarantees that eventual updates in the framework will be reflected in the way things get serialized. The toString() method was not originally designed to provide a serialized view of an object, which can later be used to get the object back, but to simply provide 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 of one belonging to a class that you defined and make such a class serializable. Then provide the following methods:
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
And, yes, they should be private. See more here: Discover the secrets of the Java Serialization API
I was wondering if there is any way or library which allows the automatic conversion of json strings to java objects ?
i.e. similar functionality provided by Backbone for javascript.
I am fully aware you can do it step by step for each field using something like:
JSONObject json = new JSONObject(jsonString);
String body = json.get("body").toString;
However I have many json files to convert and manually typing out the code for ever object I need seems tedious. Is there anyway to do it autonomously ?
I.e. provide an object template which can be populated regardless of it's fields ?
Most frameworks that use ajax allow you to set a config that will do this for you.
MyClass a = Gson().fromJson(jsonString, MyClass.class)
I'm working on an Android app. The app gets the data as JSON string (name of universities and student lists) and manipulate the app according to the data.
What will be a better approach?
Create a new Object and parse the JSON string into it, and work with the object, or
Keep the JSON string, and just use JSONObject whenever I need to grab information from the string
Or any other way?
If I'm using the new Object, how can I transfer (or share) the object with other activities in the app?
I know that for string we can use putextra().
Use objects.
I would suggest to use Jackson library,
be cause it is very fast and easy to ingrate.
You can find code examples here :
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
P.S. : Jackson is not the only library for this approach > Jackson Vs. Gson
I almost always parse the JsonObject into a specific object E.g. class University.
One benefit of doing this, is you can put it nicely into collections. E.g. HashMaps, Set or just straight List. When dealing with it as a JsonObject you won't be able to as easily work with it.
You can do things like sort it if you Object inherits Comparable, and can define equals/toString/hashCode.
There are a number of other benefits, but I think you'll find holding that data in a real data structure will give you the most benefit
I would recommend parsing the string (or using a library to do this for you!) and filling an object. This way, your model object can control the data and how it is shared with other objects, and use internal data structures to optimize usage. If you stuck with the JSON string you'd end up parsing it multiple times to pull out data.
However you decide to share the object/string across activities shouldn't affect your decision for how to model the data. You'll likely end up passing it across activities in any case.
I suggest that you use objects too.
You can use Gson library to do any conversion between json string and objects. It is very, very easy to use. http://code.google.com/p/google-gson/
To transfer the data between other activities you can make your object implement the Serializable interface, this way you can use the .putExtra() and pass it forward.
Is that the class should extend ObjectWritable class? Then how can I pass it from client to the Map and Reduce? thanks
I assume you mean to pass an object from your client code to your Mappers and Reducers?
You will have to use some form of serialization to do that, since the data is going over the wire. There are a few possibilities depending on your scenario:
Probably the best solution would be to instantiate the object in the Mappers/Reducers. To pass the information required for the constructor call, you can use the Job-Configuration.
conf.setInt("foo", 32);
conf.set("bar", "bazz");
If your object is serializable and quite small you can serialize it and include a base64 encoded version of it in the JobConf.
If the serialized objects are to big, you can use the distributed cache: http://hadoop.apache.org/common/docs/r0.20.2/mapred_tutorial.html#DistributedCache