简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM