Pedro Samú
Pedro Samú

Reputation: 1

JSON Object/Array to Java object using GSON

I have the following JSON structure received from a GET response:

[
   {
      "type":"unico",
      "line_items":{
         "meta_data":[
            {
               "id":"1",
               "key":"abc"
            },
            {
               "id":"2",
               "key":"cba"
            }
         ]
      }
   },
   {
      "type":"assinatura",
      "line_items":{
         "meta_data":{
            "4":{
               "id":"1",
               "key":"123"
            },
            "5":{
               "id":"2",
               "key":"321"
            }
         }
      }
   }
]

According to the structure the meta_data object can both be defined as a list of objects and an array of objects depending on the type.

I'm using the following definition to my LineItem.java class:

@SerializedName("meta_data")
@Expose
private MetaData metaData;

Which attends to the "type":"assinatura" type.

When parsing the JSON String to the Java object using GSON I get the error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 607 path $[0].line_items[0].meta_data

Is there a way I can have my Java class deal with both cases? From my position I can't alter the JSON structure.

Upvotes: 0

Views: 127

Answers (1)

Maulik Dodia
Maulik Dodia

Reputation: 1659

Use this JsonToPojo converter. It is very handy and It will create Pojo classes according to your Json response.

Upvotes: 0

Related Questions