Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Json array with gson

Tags:

Im trying to parse a jsonObject and can't seem to get it, here is what i got.

 json = (json data)  JsonParser parser = new JsonParser();  JsonObject rootObj = parser.parse(json).getAsJsonObject();  JsonObject paymentsObject = rootObj.getAsJsonObject("payments");   for(JsonObject pa : paymentsObject){         String dateEntered = pa.getAsJsonObject().get("date_entered").toString();     } 

But i get a foreach not applicable to type what am i missing. I've tried different ways but can't seem to get it. thanks

Json

 {  "Name":"Test 2",  "amountCollected":"1997",  "payments":[   {      "quoteid":"96a064b9-3437-d536-fe12-56a9caf5d881",      "date_entered":"2016-05-06 08:33:48",      "amount":"1962",            },   {      "quoteid":"96a064b9-3437-d536-fe12-56a9caf5d881",      "date_entered":"2016-05-06 08:33:08",      "amount":"15",            },   {      "quoteid":"96a064b9-3437-d536-fe12-56a9caf5d881",      "date_entered":"2016-05-06 03:19:08",      "amount":"20",            }  ] } 
like image 623
user1054513 Avatar asked May 25 '16 03:05

user1054513


People also ask

How to parse JSON Array Gson?

Parsing JSON with Array as Member. Gson parses JSON arrays as members without difficulty if they are non-root objects. We can use the fromJson() method in the usual manner and it will parse the JSON array correctly to the required java array or list.

How to convert JSON Array to List in Java using Gson?

TypeToken; JsonElement yourJson = mapping. get("servers"); Type listType = new TypeToken<List<String>>() {}. getType(); List<String> yourList = new Gson().

How to parse JSON Array of Objects in Java?

//Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser. parse(new FileReader("E:/players_data. json")); Retrieve the value associated with a key using the get() method.


1 Answers

Now that we can see the data, we can see that payments is in fact an array (values uses []).

That means you need to call rootObj.getAsJsonArray("payments") which returns a JsonArray, and it is an Iterable<JsonElement>, which means your loop should be for(JsonElement pa : paymentsObject).

Remember, each value of the array can be any type of Json element (object, array, string, number, ...).

You know that they are JsonObject, so you can call getAsJsonObject() on them.

json = (json data) JsonParser parser = new JsonParser(); JsonObject rootObj = parser.parse(json).getAsJsonObject(); JsonArray paymentsArray = rootObj.getAsJsonArray("payments"); for (JsonElement pa : paymentsArray) {     JsonObject paymentObj = pa.getAsJsonObject();     String     quoteid     = paymentObj.get("quoteid").getAsString();     String     dateEntered = paymentObj.get("date_entered").getAsString();     BigDecimal amount      = paymentObj.get("amount").getAsBigDecimal(); } 
like image 149
Andreas Avatar answered Sep 21 '22 13:09

Andreas