Java 使用 gson 循环 Json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37427179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop Json array with gson
提问by user1054513
Im trying to parse a jsonObject and can't seem to get it, here is what i got.
我试图解析一个 jsonObject 并且似乎无法得到它,这就是我得到的。
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
但是我得到一个 foreach 不适用于键入我缺少的内容。我尝试了不同的方法,但似乎无法理解。谢谢
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",
}
]
}
采纳答案by Andreas
Now that we can see the data, we can see that paymentsisin fact an array (values uses []).
现在,我们可以看到的数据,我们可以看到,payments是实际上是一个数组(值的用途[])。
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).
这意味着您需要调用rootObj.getAsJsonArray("payments")which 返回 a JsonArray,并且它是 an Iterable<JsonElement>,这意味着您的循环应该是for(JsonElement pa : paymentsObject)。
Remember, each value of the array can be any type of Json element (object, array, string, number, ...).
请记住,数组的每个值都可以是任何类型的 Json 元素(对象、数组、字符串、数字等)。
You know that they are JsonObject, so you can call getAsJsonObject()on them.
你知道他们是JsonObject,所以你可以打电话getAsJsonObject()给他们。
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();
}

