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", } ] }
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.
TypeToken; JsonElement yourJson = mapping. get("servers"); Type listType = new TypeToken<List<String>>() {}. getType(); List<String> yourList = new Gson().
//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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With