20

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?

2
  • Is there more direction you can provide about the problem? What is the input, where are you getting it from, what are you trying? Commented Apr 24, 2012 at 6:08
  • The Proplem is when I try to get a Objcet[] array usin gson.fromJson() I get a null vule , I get this JSON array from a PHP page : Commented Apr 24, 2012 at 6:26

2 Answers 2

56

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);
...
Sign up to request clarification or add additional context in comments.

5 Comments

what is List<Asd> asd here?
Can anyone help me with this - stackoverflow.com/questions/27666558/… ?
FYI, for Type is java.lang.reflect.Type. There're million Type classes so auto complete might be confusing.
If the JsonArray is of a known type the best way might be stackoverflow.com/questions/43133484/…
THis doesn't seem to work. "Asd" is not defined.
0

For example your service has such response

[ new SomeObject(), new SomeObject(), new SomeObject() ] - this is jsonArray

SomeObject - is a class instance of that your array is contains.

You should use special class TypeToken (docs here https://sites.google.com/site/gson/gson-user-guide)

Type type = new TypeToken<List<SomeObject>>(){}.getType();



String jsonArray = restResponse.getPayload(); - you get response as String
List<SomeObject > list = new Gson().fromJson(jsonArray, type);

Done!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.