我之前做过 JSON 解析,但这个对我不起作用。我不知道为什么。这是一个非常简单的结构,我仍然无法修复它。
这是我从我的 URL 获得的响应。
{
"BalanceItems" : [{
"BalanceItem" : {
"BalanceType" : "General Cash",
"Description" : "Prepay Credit",
"ShortDescription" : "Your bal is $",
"Value" : 187.95,
"Unit" : "$NZ",
"ExpiryValue" : "",
"ExpiryDate" : "18\/02\/2012"
}
}, {
"BalanceItem" : {
"BalanceType" : "Me 2 U",
"Description" : "Me2U Credit",
"ShortDescription" : "Your bal is $",
"Value" : 176.86,
"Unit" : "$NZ",
"ExpiryValue" : "176.86",
"ExpiryDate" : "12\/06\/2011"
}
}, {
"BalanceItem" : {
"BalanceType" : "Rate Plan Recharge Reward",
"Description" : "Your 'top up and get' special rates",
"ShortDescription" : "Your 'top up and get' rates are yours until",
"Value" : ""
}
}
]
}
这是我的代码
try{
URL url = new URL("myurl");
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
String response = builder.toString();
JSONObject jar = new JSONObject(response);
Log.e("Object Size","Object Size "+ jar.length());
// Here i should get the size of object as 3 because i have three object of type "BalanceItem"
}
catch (Exception e) {
// TODO: handle exception
}
最佳答案
您有一个包含 JSONArray 的 JSON 对象。您需要获取 JSONArray:
JSONArray array = jar.getJSONArray("BalanceItems");
Log.e("Object Size","array Size "+ array.length());
在此处检查 API:
http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray%28java.lang.String%29
http://www.json.org/javadoc/org/json/JSONArray.html
附录:
数组依次包含多个 JSONObject。您需要遍历它并获取每一个:
for (int i=0; i<array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Log.d ("Balance "+i, obj.getString("Value") + " " + obj.getString("Unit"));
}
你明白了。在我的头顶上输入这里,所以要小心打字错误。
关于android - JSON 解析在 Java 中无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983967/