简体   繁体   English

通过GSON将json字符串转换为对象

[英]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. 我正在尝试将json字符串解析为java对象,但是我不确定对象的层次结构。

below is the json string 下面是json字符串

{  
   "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. 在这里,数字12是动态的,可以去到任何数字,我试图创建一个外部对象,有一个地图类型密钥字符串和值对象资料表的。 The map having variable name TABLE_Detail . 具有变量名TABLE_Detail的映射。 but the TableData object is always null. 但是TableData对象始终为null。 TableData object has all the variables. TableData对象具有所有变量。

Please help me on how to convert this json string to object. 请帮助我如何将此json字符串转换为对象。

Change 1 to table1 and 2 to table2: 将1更改为table1,将2更改为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: 如果将json格式修改为“ Koen Van Looveren”,则提及:

public class TableDetails {
    List<TableData> tables;

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

The table class: Table.java: 表类: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>> . 您可以尝试将其反序列化为Map<String, Map<String, TableData>> The reason why Map<String, TableData> doesn't work it that the pesudo-array is wrapped in another object. 伪数组包装在另一个对象中的原因Map<String, TableData>不能正常工作。

The following example converts a response into a List<TableData> : 以下示例将响应转换为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. 使用Gson时,对于这样痛苦的json结构,您有两种选择。

  1. using Gson parsing json as Map and write some class access returned Map.this mode works fine for access data only! 使用Gson将json解析为Map并编写一些类访问返回的Map。此模式仅适用于访问数据!

     //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 TypeAdapter,但这种方式可能会更复杂。如果您对编写自定义TypeAdapter感兴趣,则有一个我为提取json根而编写的演示。 gson-enclosing-plugin GSON-包围-插件

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. 我可以映射动态值1、2,因为映射键和值使用@SerializedName gson注释对应地映射到TableData对象属性。

http://findnerd.com/list/view/Parse-Json-Object-with-dynamic-keys-using-Gson-/24094/ 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 在json中使用数组时,您需要使用[用于打开,使用]用于关闭

{
  "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"
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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