【发布时间】:2015-03-03 21:51:09
【问题描述】:
在 Android 上,我通过以下方法检索 JSON 对象;
JSONObject tempObj = jsonObj.getJSONArray("result");
为了确保它正确,我把它系统化了;
System.out.println(tempObj);
它给出以下输出;
{
"result": [
{
"telMobile": "5555555",
"products": [
{
"id": "113245",
"price": "749.0",
"unitId": 1
},
{
"id": "52589",
"price": "7.35",
"unitId": 1
}
]
}
]
}
所以,JSONObject tempObj 内部有一个名为“products”的 JSONArray,每个产品都有“id”、“price”和“unitId”三个字段。但是,当我解析此对象时,我收到“没有 unitId 值”错误。
for (int k = 0; k < tempObj.getJSONArray("products").length(); k++) {
JSONObject tempProduct = tempObj.getJSONArray("products").getJSONObject(k);
products.add(new Product(tempProduct.getString("id"), tempProduct.getString("price"),tempObj.getInt("unitId")));
}
这完全没有意义。我可以正确获取其他字段。这意味着当我不检索 unitId 而是写 1 时;
for (int k = 0; k < tempObj.getJSONArray("products").length(); k++) {
JSONObject tempProduct = tempObj.getJSONArray("products").getJSONObject(k);
products.add(new Product(tempProduct.getString("id"), tempProduct.getString("price"),1));
}
然后正确地构造对象。我尝试将其作为 String 获取,然后转换为 int as;
Integer.parseInt(tempProduct.getString("unitId"));
但是 unitId 仍然给出错误。我认为服务器端会有问题,但 JSONObject 正确到达,因为我可以从 logcat 输出中看到它。这是一个简单的整数,怎么会导致这样的错误?这样的案例背后是否存在一些不同的问题?
【问题讨论】:
-
是否抛出异常?
-
我只是想从错误的对象中获取 unitId