Newaj
Newaj

Reputation: 4448

How to parse json array having dynamic keys using Retrofit 2

I am trying to fetch json response using retrofit 2. My json response looks like this :

[
    0 : {
        type : "video",
        format : "mp4",
        size : "10mb"
        },
    1 : {
        type : "audio",
        format : "mp3",
        size : "10mb"
        },
    2 : {
        type : "text",
        format : "pdf",
        size : "10mb"
        }
]

How should my model class look like? I can't understand as it has dynamic keys.

Upvotes: 0

Views: 1277

Answers (3)

Matias Olocco
Matias Olocco

Reputation: 509

So, as people already said, if you change your json to be valid:

[  
   {  
      "type":"video",
      "format":"mp4",
      "size":"10mb"
   },
   {  
      "type":"audio",
      "format":"mp3",
      "size":"10mb"
   },
   {  
      "type":"text",
      "format":"pdf",
      "size":"10mb"
   }
]

Then you can create your class, for instance:

public class Test {
    public String type;
    public String format;
    public String size;
}

And then, with Gson:

Type testType = new TypeToken<ArrayList<Test>>(){}.getType();
ArrayList<Test> list = new Gson().fromJson(json, testType);

On the other hand, with retrofit2 you can get the Gson converter to do the job for you.

Upvotes: 2

Nick
Nick

Reputation: 595

first of all this is invalid/incomplete JSON. The valid version would look something like this

{
  "items": [
    {
      "0": {
        "type": "video",
        "format": "mp4",
        "size": "10mb"
      }
    },
    {
      "1": {
        "type": "audio",
        "format": "mp3",
        "size": "10mb"
      }
    },
    {
      "2": {
        "type": "text",
        "format": "pdf",
        "size": "10mb"
      }
    }
  ]
}

and it would safely deserialize to this

    class Item{
        String type;
        String format;
        String size;
    }

    class Response{
        List<Map<Integer,Item>> items;
    }


//....

Response response = new Gson().fromJson(yourJson, Response.class);

As an alternative solution, as I am sure you can't change the JSON format, change the [] to {} in your JSON string and deserialize it like this

Map fieldMap = (Map)new Gson().fromJson(json, Map.class);

it should give you a LinkedTreeMap of all your data

Upvotes: 3

Arash GM
Arash GM

Reputation: 10395

This is not a valid Json as you can try that on https://jsonlint.com/ , you can change your response to :

[  
   {  
      "type":"video",
      "format":"mp4",
      "size":"10mb"
   },
   {  
      "type":"audio",
      "format":"mp3",
      "size":"10mb"
   },
   {  
      "type":"text",
      "format":"pdf",
      "size":"10mb"
   }
]

Upvotes: 5

Related Questions