【发布时间】:2011-05-12 20:20:01
【问题描述】:
我之前已经完成了 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
}
【问题讨论】:
-
发布您的 Logcat、错误、代码,然后人们会尽力帮助您。
-
解析 JSON 的代码是什么样的?
-
其实
jar.length()是1。它只包含BalanceItems数组。 JSONArray BalanceItems 长度应为 3。 -
如果我没记错的话 BalanceItems 是一个数组,而 BalanceItem 是对象。那么如何获取 BalanceItem 对象并获取其值。
-
Sujit,请用您的代码编辑您的问题。