在 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));
}
然后对象被正确构造。我尝试将其作为字符串获取,然后将其转换为 int ;
Integer.parseInt(tempProduct.getString("unitId"));
但是 unitId 仍然报错。我认为服务器端会有问题,但 JSONObject 正确到达,因为我可以从 logcat 输出中看到它。这是一个简单的整数怎么会导致这样的错误?这样的案例背后会不会隐藏着一些不同的问题?
最佳答案
你应该改变
tempObj.getInt("unitId")
到
tempProduct.getInt("unitId")
实际上,您正试图从 tempObj
获取值。那是错的。没有值(value)。所以不是从 tempProduct
关于android - JSON - x 没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27795110/