Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a JSON array of objects using Gson library?

Tags:

I am facing an issue while I am trying to deserialize a JSON array of objects using the Gson library.

An example of the JSON array:

[
    {"ID":1,"Title":"Lion","Description":"bla bla","ImageURL":"http:\/\/localhost\/lion.jpg"},
    {"ID":1,"Title":"Tiger","Description":"bla bla","ImageURL":"http:\/\/localhost\/tiger.jpg"}
]

What do you think? What is the proper Java code to deserialize such a JSON response?

like image 267
Nashwan Doaqan Avatar asked Apr 24 '12 06:04

Nashwan Doaqan


People also ask

How do I deserialize JSON with Gson?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.

What does Gson toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.

What is the difference between Gson and Jackson?

Both Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.


1 Answers

To deserialize a JSONArray you need to use TypeToken. You can read more about it from GSON user guide. Example code:

@Test
public void JSON() {
    Gson gson = new Gson();
    Type listType = new TypeToken<List<MyObject>>(){}.getType();
    // In this test code i just shove the JSON here as string.
    List<Asd> asd = gson.fromJson("[{'name':\"test1\"}, {'name':\"test2\"}]", listType);
}

If you have a JSONArray then you can use

...
JSONArray jsonArray = ...
gson.fromJson(jsonArray.toString(), listType);
...
like image 194
Kirstein Avatar answered Sep 20 '22 21:09

Kirstein