6

I'm using retrofit to handle rest-api calls. I have a rest API that returns the following json

    "MyObject": {
      "43508": {
        "field1": 4339,
        "field2": "val",
        "field3": 15,
        "field4": 586.78
      },
      "1010030": {
        "field1": 1339,
        "field2": "val212",
        "field3": 1,
        "field4": 86.78
      },...
    }

Please notice that the object MyObject contains objects with a name that is actually an id. For all the other rest APIs I'm using retrofit without problems. In this case it seems not possible to use the standard approach: defining a class containing the fields expected in the response.

Is there a way to transform this json into a json containing an array of

{
    "field1": xxx,
    "field2": "yyy",
    "field3": www,
    "field4": zzz
}

Or is there a better way to deal with this problem without going back to "manually" parsing the json?

1048576
  • 615
  • 9
  • 27

3 Answers3

2

Try to use next approach:

public class Response {

    Map<String, YourObject> MyObject;
    // getter, setter
}

public interface GitHubService {
  @GET("some_path")
  Call<Response> listMyObjects();
}

All you objects will be parsed to Map. You can get the list of all ids via keySet() method or list all entries with entrySet().

Ilya Tretyakov
  • 6,848
  • 3
  • 28
  • 45
1

Try putting the annotation, SerializedName(nameOfField) over the variable name.

@SerializedName("13445345")
MyObject object;
CodeCody
  • 320
  • 2
  • 5
  • 2
    the problem is that there is a huge number of possible ids. I can't set the SerializedName like that – 1048576 May 31 '16 at 16:03
0

Well my idea is quite manual, but it should work. I will not copy and paste another person's answer here, so take a look at this answer to see how to loop through all of the myObject's keys. Then for each of those keys, make a new JSONArray and add key value pair of fieldX-valueX.

This is just a basic idea, since I think you can handle the code yourself, you seem like a guy who knows his way around the simple stuff.

Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45