true-mt
true-mt

Reputation: 357

How to map json dictionary automatically with gson

Setup: - Android - Retrofit 2 - Gson

My Server json looks like this:

{
 "myList1": 
  {
   "1": (<- variable number)
    {
      "id":"1","name":"user123"
    }, 
   "2"{},...}, 
 "myList2": 
  {
   "299": (<- variable number)
    {
     "id":"20","name":"user42"
    }, 
   "300":
   {},...}
}

The first node: "myList1" and "myList2" is fix.

Then the second node contains a variable number

And the second node holdes an user object.

-> How do I define the response for the second list with gson?

-> The number and the count of the entries is variable

My Response Mapping looks like:

public class ResponeDef {
   @Gson.Named("myList1")
   ResponeListDef list1;

   @Gson.Named("myList2")
   ResponeListDef list1;
}

public class ResponeListDef {
   @Gson.Named("??")
   ResponeListEntryDef entry1

   @Gson.Named("??")
   ResponeListEntryDef entry2;
}

public class ResponeListEntryDef {
   @Gson.Named("id")
   int id;

   @Gson.Named("name")
   String userName;
}

Upvotes: 0

Views: 582

Answers (1)

Anuj
Anuj

Reputation: 1940

If you have control over the API, the easiest solution would be to convert the response format to

{
 "myList1": 
  [
    {
      "id":"1","name":"user123"
    }, 
   {},...], 
 "myList2": 
  [
    {
     "id":"20","name":"user42"
    },
   {},...]
}

If you do not, then you can parse this using a custom TypeAdapter.

Change your response def to

public class ResponeDef {
   @Gson.Named("myList1")
   List<ResponseListEntryDef> list1;

   @Gson.Named("myList2")
   List<ResponseListEntryDef> list1;
}

public class ResponeListEntryDef {
   @Gson.Named("id")
   int id;

   @Gson.Named("name")
   String userName;
}

and create a custom TypeAdapter as

class CustomAdapter extends TypeAdapter<ResponseDef> {

    @Override
    public void write(JsonWriter out, ResponseDef value) throws IOException {
        // loop over lists and write them to out
    }

    @Override
    public ResponseDef read(JsonReader in) throws IOException {
        // loop over items in jsonReader and initialize the lists
        return responseDef;
    }
}

You can then register the type adapter with Gson with

Gson gson = new GsonBuilder()
                .registerTypeAdapter(ResponseDef.class, new CustomAdapter())
                .create();

Upvotes: 1

Related Questions