Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson parsing from List of Maps. How?

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?

like image 346
D.K. Avatar asked Sep 03 '25 13:09

D.K.


2 Answers

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"));
like image 164
giampaolo Avatar answered Sep 05 '25 17:09

giampaolo


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.
  }
like image 41
Asif Bhutto Avatar answered Sep 05 '25 16:09

Asif Bhutto