【问题标题】:Gson parsing from List of Maps. How?从地图列表中解析 Gson。如何?
【发布时间】:2013-12-19 09:13:38
【问题描述】:

JSON 格式解析有问题

{
    "retval": [
        {
            "DocumentEntityCD": "AccOperation",
            "DocumentType": "Document Accounting operation",
            "DocNumber": "12345",
            "DebitAccountCode": "201",
            "CreditAccountCode": "201",
            "Amount": 75.5
        },
        {
            "GeneralJournalID": "5NE5DsWHo0GD_VkiJO_a1Q",
            "DocumentUID": "sV6Pqw-_CkuAtiZsuzZNcA",
            "Date": "2012051521",
            "DocumentEntityCD": "AccOperation",
            "DocumentType": "Document Accounting operation",
            "Amount": 555
        }
    ],
    "time": 0
}

正确解析时,Gson 对象应该是什么样子?

【问题讨论】:

    标签: list dictionary object gson


    【解决方案1】:

    我会用这样的类解析:

       public static class Container{
          public List<Map> retval;
          public Integer time;
       }
    

    因此提取您感兴趣的值非常容易。

       Gson g = new Gson();
       Container c = g.fromJson(json, Container.class);
       System.out.println(c.retval.get(0).get("DocNumber"));
    

    【讨论】:

      【解决方案2】:

      你可以像这样简单地做到这一点

       final Type typeOf = new TypeToken<Map<String, List<Map<String,String>>>>(){}.getType();
       final Map<String, List<Map<String,String>>> newMap = gson.fromJson(Your_Json_String, typeOf);
           // get list of Maps
       final List<Map<String,String>> listOfMaps = newMap.get("retval");
      
       for (Map<String, String> map : listOfMaps) {
      
          // do your stuff here, iterate map here and get key values.
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-08
        • 2014-11-11
        • 1970-01-01
        相关资源
        最近更新 更多