简体   繁体   中英

converting json string to object through GSON

I am trying to parse a json string to java object but i am not sure on the object hierarchy.

below is the json string

{  
   "TABLE_Detail":{  
      "1":{  
         "TABLE":"table1",
         "RUN_DATE":"20170313",
         "SEQ_NUM":"123",
         "START_TIME":"20170313133144",
         "END_TIME":"20170313133655"
      },
      "2":{  
         "TABLE":"table2",
         "RUN_DATE":"20170313",
         "SEQ_NUM":"123",
         "START_TIME":"20170313133142",
         "END_TIME":"20170313133723"
      }
   }
}

Here the number 1 , 2 are dynamic and can go up to any number, I tried to create a outer object and have a Map of type key String and value as object TableData. The map having variable name TABLE_Detail . but the TableData object is always null. TableData object has all the variables.

Please help me on how to convert this json string to object.

Change 1 to table1 and 2 to table2:

public class TableDetails {
    private TableData table1;

    private TableData table2;

    public TableDetails(){

    }

    // getter and setter
}

And if modify json format to "Koen Van Looveren" mentioned:

public class TableDetails {
    List<TableData> tables;

    public TableDetails() {
    }
    // getter and setter
}

The table class: Table.java:

public class TableData {
    private String table;

    private String run_date;

    private String seq_num;

    private String start_time;

    private String end_time;

    public TableData() {
    }

    // getter and setter
}

You can try deserialize it into a Map<String, Map<String, TableData>> . The reason why Map<String, TableData> doesn't work it that the pesudo-array is wrapped in another object.

The following example converts a response into a List<TableData> :

public List<TableData> deserialize(String json) {
    return Gson().<Map<String, Map<String, TableData>>>fromJson(json, new TypeToken<Map<String, Map<String, TableData>>>(){}.getType())
        .values().iterator().next()
        .entrySet().stream()
        .sorted(Comparator.comparingInt(e -> Integer.parseInt(e.getKey())))
        .map(Map.Entry::getValue)
        .collect(Collectors.toList());
}

you have two choice for such painfully json structure when using Gson.

  1. using Gson parsing json as Map and write some class access returned Map.this mode works fine for access data only!

     //usage TableDetails details=new TableDetails(gson.fromJson(json, Map.class)); //classes class TableDetails { private Map<String, Map> context; public TableDetails(Map root) { this.context = (Map<String, Map>) root.get("TABLE_Detail"); } public int size() { return context.size(); } public Table get(String key) { return new Table(context.get(key)); } } class Table { private Map context; public Table(Map context) { this.context = context; } public String getName() { return get("TABLE"); } private <T> T get(String name) { return (T) context.get(name); } ... } 
  2. write your own Gson TypeAdapter,but this way may be more complex.if you interesting on write custom TypeAdapter there is a demo that I written for extract json root. gson-enclosing-plugin

I was in a search for the solution, and i came across one of the site where the solution worked. i wanted to credit the below site. Thanks for all the support.

I am able to map the dynamic value 1, 2 as map keys and values are mapped correspondingly to the TableData object properties using @SerializedName gson annootation.

http://findnerd.com/list/view/Parse-Json-Object-with-dynamic-keys-using-Gson-/24094/

When using an array in json you need to use [ for opening and ] for closing

{
  "TABLE_Detail": [
    {
      "TABLE": "table1",
      "RUN_DATE": "20170313",
      "SEQ_NUM": "123",
      "START_TIME": "20170313133144",
      "END_TIME": "20170313133655"
    },
    {
      "TABLE": "table2",
      "RUN_DATE": "20170313",
      "SEQ_NUM": "123",
      "START_TIME": "20170313133142",
      "END_TIME": "20170313133723"
    }
  ]
}

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