我想在Volley Library中解析这个JSON。我已经设置了我要解析配方和图像名称的所有内容。问题是我想要同时解析三个配方,但这里它有相同的对象名称Recipe,我不知道如何解析三个不同TextView的相同对象名称。
以下是JSON格式:link
这是我尝试的代码,但它给了我一个名字而不是三个不同的名字:
try {
JSONArray list = response.getJSONArray("hits");
Log.v ("MISH", "List: " + list);
for (int x = 0; x<list.length(); x++) {
JSONObject obj = list.getJSONObject(x);
JSONObject main = obj.getJSONObject("recipe");
String label = main.getString("label");
String image = main.getString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
答案 0 :(得分:1)
试试这个。
在代码中使用optString
:
try {
if (TextUtils.isEmpty(response)) {
Toast.makeText(this, "response is null", Toast.LENGTH_SHORT).show();
return;
}
JSONObject jsonObject = new JSONObject(response);
JSONArray hits = jsonObject.getJSONArray("hits");
// edited here ,add data in your code
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2
for (int i = 0; i < hits.length(); i++) {
JSONObject jo = hits.getJSONObject(i);
JSONObject recipe = jo.getJSONObject("recipe");
String label = recipe.optString("label");
String image = recipe.optString("image");
Picasso.with(getApplicationContext()).load(image).into(recipeOne);
Log.v("FISH", "NAME FATCH: " + label);
recipeOneText.setText(label);
}
} catch (JSONException e) {
e.printStackTrace();
}
修改强>
// If your don't have to much data in your code , you can do like this .
JSONObject jo1 = hits.getJSONObject(0);
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2