Skip to content
wizzardo edited this page Sep 7, 2014 · 10 revisions

Json parsing

Let's parse json like this one:

{
    "name": "John",
    "id": 12345,
    "messages":[
        {
            "date": "2014-08-26T10:04:03Z",
            "message": "hi, it's my first message here"
        },
        {
            "date": "2014-08-26T10:04:13Z",
            "message": "is anybody here?"
        }
    ]
}

with JsonTools it will be like this:

JsonObject data = JsonTools.parse(json).asJsonObject();
String name = data.get("name").asString();
int id = data.getAsInteger("id");
Map<Date,String> messages = new TreeMap<Date,String>();
for (JsonItem item : data.get("messages").asJsonArray()) {
    JsonObject message = item.asJsonObject();
    messages.put(message.get("date").getAs(Date.class), 
                    message.getAsString("message"));
}

Or, if we have classes...

class User {
    String name;
    long id;
    List<Message> messages;
}

class Message {
    String message;
    Date date;
}

...then code will be much simpler:

User user = JsonTools.parse(json, User.class);

Also, JsonTools can parse into list or map:

List<Message> messages = JsonTools.parse(json, List.class, Message.class);
JsonTools.parse("{foo: bar}", Map.class, String.class,String.class);
//  or even more complex
JsonTools.parse("{foo: [1,2,3]}", Map.class, 
    new Generic(String.class), new Generic(int[].class))
JsonTools.parse("{foo: [1,2,3]}", Map.class, 
    new Generic(String.class), new Generic(List.class, Integer.class))

Creating json

JsonTools can serialize any java object for you:

String json = JsonTools.serialize(user);
// {"name":"John","id":12345,"messages":[{"date":"2014-08-26T10:04:03Z", ...

json = JsonTools.serialize(new int[]{1,2,3});
//[1,2,3]

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
json = JsonTools.serialize(map);
//{"one":1,"two":2}

Or you can build json manually:

String json = new JsonObject()
    .append("foo", "bar")
    .append("object", new JsonObject()
                    .append("key", "value")
    )
    .append("array", new JsonArray()
                    .append(1)
                    .append(2)
                    .append(3)
    ).toString()
//{"foo":"bar","object":{"key":"value"},"array":[1,2,3]}    
Clone this wiki locally