user1054513 user1054513 - 6 months ago 66
JSON Question

Loop Json array with gson

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

Answer

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();
}
Comments