JSON - 没有x的值

Far*_*ıcı 3 android json

在Android上,我通过以下方法检索JSON对象;

JSONObject tempObj = jsonObj.getJSONArray("result");
Run Code Online (Sandbox Code Playgroud)

为了确保它正确,我制定了它;

System.out.println(tempObj);
Run Code Online (Sandbox Code Playgroud)

它给出了以下输出;

{
  "result": [
    {
      "telMobile": "5555555",
      "products": [
        {
          "id": "113245",
          "price": "749.0",
          "unitId": 1
        },
        {
          "id": "52589",
          "price": "7.35",
          "unitId": 1
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

因此,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")));
}
Run Code Online (Sandbox Code Playgroud)

这完全没有意义.我可以正确地获得其他字段.这意味着当我不检索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));
}
Run Code Online (Sandbox Code Playgroud)

然后正确构造对象.我尝试将它作为String然后转换为int as;

Integer.parseInt(tempProduct.getString("unitId"));
Run Code Online (Sandbox Code Playgroud)

但是unitId仍然会出错.我认为服务器端会出现问题,但JSONObject正确到达,因为我可以从logcat输出中看到它.这是一个简单的整数怎么会导致这样的恐怖?这种情况背后会有一些不同的问题吗?

M D*_*M D 5

你应该改变

tempObj.getInt("unitId")
Run Code Online (Sandbox Code Playgroud)

tempProduct.getInt("unitId")
Run Code Online (Sandbox Code Playgroud)

实际上你正试图从中获取价值tempObj.那是错的.没有价值.所以不要从中获取价值tempProduct