Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit to parse json with an indefinite number of object names

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?

like image 292
1048576 Avatar asked Oct 18 '22 08:10

1048576


2 Answers

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().

like image 90
Ilya Tretyakov Avatar answered Nov 15 '22 05:11

Ilya Tretyakov


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

@SerializedName("13445345")
MyObject object;
like image 37
CodeCody Avatar answered Nov 15 '22 05:11

CodeCody