0

The JSON result for getUsers I get from the server looks like this:

{
  "result": [
    {
      "meta": {
        "rows": "3"
      }
    },
    {
      "items": [
        {
          "id": "1",
          "name": "Steve",
          "age": "30"
        },
        {
          "id": "2",
          "name": "Mary",
          "age": "29"
        },
        {
          "id": "3",
          "name": "Bill",
          "age": "58"
        }
      ]
    }
  ]
}

How can I deserialize it by GSON in my android app (I'm using retrofit)?
I can't imagine any wrapper classes because of the different object types in result.
Any help would be appreciated!

A2i_
  • 398
  • 3
  • 13
  • I'm using retrofit to deserialize. So I created a `Meta` class and a `UserList` class with a `List items` but I just can't get them fit into this weird array. – A2i_ May 27 '15 at 15:55
  • So, how did it go? Did you solve the problem? If yes, choose an answer and accept it, or write your own answer if you solved it in a different way. – Display Name May 30 '15 at 20:25
  • I created a `TypeAdapterFactory` that went through the JSON. I was about 70% done when the API was changed. The new API has a "normal" structure, so I don't need custom parsing anymore. But just in interest of the solution I plan to work out the last 30% when I got some free time. I will post the results here. – A2i_ Jun 02 '15 at 08:17

2 Answers2

0

For good example Converting JSON to Java

Other way, you can convert your json to a java object

Please use org.json library http://www.json.org/java/index.html

Then, for example

json = new JSONObject(YOUR_JSON).getJSONObject("result");
JSONArray items = data.getJSONArray("items");
String name = items.getJSONObject(0).getString("name");
Community
  • 1
  • 1
baroni
  • 176
  • 8
0

You can write a TypeAdapter for a type that will be (de)serialized to(from) array. You can even make it generic, so it will work with type like Pair<A, B>. Here is an example for non-generic type: https://github.com/cakoose/json-tuple-databinding-examples/blob/master/java/src/GsonEntryCustomizer.java — it (de)serializes Entry to(from array).
Disclaimer — I have not written nor tested that code, but it seems legit.

If you only encounter such problem once (like in your example), you may not bother making it generic, just write TypeAdapter for your specific pair of 2 different classes. The reading code is quite straightforward:

in.beginArray();
SomeClass1 info1 = gson.getAdapter(SomeClass1.class).read(in);
SomeClass2 info2 = gson.getAdapter(SomeClass2.class).read(in);
in.endArray();
return new SomeContainerClass(info1, info2);

(see https://github.com/cakoose/json-tuple-databinding-examples/blob/master/java/src/GsonEntryCustomizer.java#L52)

Display Name
  • 8,022
  • 3
  • 31
  • 66