tags:

views:

7663

answers:

5

Hi all, I want to be able to access properties from a json string within my java action method. The string is available by simply saying myJsonString = object.getJson(); Below is an example of what the string can look like:

{'title': 'Computing and Information systems','id':1,'children': 'true','groups':
  [{'title': 'Level one CIS','id':2,'children': 'true','groups':[{'title': 'Intro To 
 Computing and Internet','id':3,'children': 'false','groups':[]}]}]}

In this string every json object contains an array of other json objects. The intention is to extract a list of id's where any given object possessing a group property that contains other json objects. I looked at google's Gson as a potential json plugin. Can anyone offer some form of guidance as to how I can generate java from this json string?

Thank you, Kind regards.

+4  A: 

If you visit this page you will find several Java classes that can help with this. For example, the JSONObject and the JSONArray classes. They are designed to read in a JSON String and provide access to their properties via a get() method.

Vincent Ramdhanie
I used this library in a project and it stinks. Example: JSONObject#getNames(JSONObject) returns null instead of an empty List or array if no names are available.
Malax
@Malax Thanks for the heads up. Hopefully one of the other suggestions would work better for the OP.
Vincent Ramdhanie
@Malax Since you have access to the code, couldn't you change JSONObject#getNames to return whatever you'd like in that case? But that JSON library could still stink for other reasons (never used them personally, but I know we're using them at work).
Jon Homan
Well, json.org default lib is rather rudimentary. I wouldn't choose it for any new project -- most alternatives from the page are much better. People are just using it because it has been around for years, and so others have used, and recommend it to new users... basic s/w development inertia.
StaxMan
+6  A: 

The XStream library also supports JSON: http://xstream.codehaus.org/json-tutorial.html.

Dave
+32  A: 

We have chosen Google Gson because it has the best support for Generics and nested beans.

Your example can be solved the following way:

package com.stackoverflow.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Fairly simple, isn't it? Just have a suitable Javabean and call Gson#fromJson().

BalusC
+1 Great example. Simple and to the point!
Fedearne
Thanks BalusC, I used Gson and the concept is quite simple to grasp.
Binaryrespawn
You're welcome.
BalusC
Performant? Have you actually measured it? While GSON has reasonable feature set, I thought performance was sort of weak spot (as per [http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html])As to example: I thought GSON did not really need setters, and was based on fields. So code could be simplified slightly.
StaxMan
It is fast enough, sure if you see what it all can do with javabeans, nested javabeans and generics. The javabean getters/setters have other purposes in other layers and does not slowdown so I would just keep them there.
BalusC
I use it in an android app. It is not the fastest possible solution but it is simple enough to program to justify the lack of performance for the user until now. Maybe in a later version of the app it will be removed for a faster solution.
Janusz
Wrt speed, if it's fast enough, it's fast enough. I just commented on reference to expected good performance.Feature-set wise Jackson handles all the same nesting, layering, generics, so that's not where speed difference comes from.Having getters and setters does not impact performance in any measurable way (for packages I am aware of), so definitely can have them there.
StaxMan
A: 

If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.

Juanma
+2  A: 

Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard). Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Jor