Gson parsing from List of Maps. How?

我的未来我决定 提交于 2019-12-24 01:26:02

问题


Have an issue with JSON format parsing

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

How Gson should Object should looks like for right parsing?


回答1:


I would parse with a class like this:

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

so that extracting the values you are interested in is quite easy.

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



回答2:


You can do it simply like this

 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.
  }


来源:https://stackoverflow.com/questions/20677492/gson-parsing-from-list-of-maps-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!