我正在尝试从如下所示的JSON数组中获取JSON数据:
{
"common": [
{
"food_name": "eggs",
"serving_unit": "large",
"tag_name": "raw eggs",
"serving_qty": 1,
"common_type": null,
"tag_id": "775",
"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/775_thumb.jpg"
},
"locale": "en_US"
},
这就是我正在使用的:
public class GetDietData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String calories = "UNDEFINED";
try {
URL urlForGetRequest = new URL("https://trackapi.nutritionix.com/v2/search/instant?query=egg");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("x-app-key", "REMOVED");
connection.addRequestProperty("x-app-id", "REMOVED");
InputStream stream = new BufferedInputStream(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject();
JSONArray common = jsonRes.getJSONArray("common");
for (int i=0; i<common.length(); i++)
{
JSONObject jsonObj = common.getJSONObject(i);
calories = jsonObj.getString("food_name");
}
connection.disconnect();
} catch (IOException | JSONException e) {
editText=(findViewById(R.id.editTextDiet));
e.printStackTrace();
}
return calories;
}
@Override
protected void onPostExecute(String calories) {
if (calories == "UNDEFINED") {
Toast.makeText(Diet.this, "Food not found", Toast.LENGTH_LONG).show();
} else {
editText=(findViewById(R.id.editTextDiet));
editText.setText(calories);
}
}
}
我有以下问题:
W/System.err: org.json.JSONException: No value for common
at org.json.JSONObject.get(JSONObject.java:392)
所以问题似乎是“ common”数组没有值,因此找不到长度?我不确定为什么它看不到“普通”数组,因为我已经看过许多其他有关从数组中获取对象的问题,并且每次都相同地复制代码,但结果相同。如果我仅使用一个JSONObject并忽略了整个数组,那么我可以在stacktrace中看到它正在尝试将整个数组下载到该对象中,这意味着GET请求或API密钥绝对没有问题。 谢谢。
答案 0 :(得分:2)
您得到的错误是因为您没有将String响应传递给jsonObject
,所以它无法在空对象中找到任何东西
解决方法是
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");