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?

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

@SerializedName("13445345")
MyObject object;

1 Comment

the problem is that there is a huge number of possible ids. I can't set the SerializedName like that
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.

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.