为什么不能在java中提取Json数组?

时间:2017-03-03 09:27:48

标签: java android json loops

我有一个餐馆列表对象,并在该餐厅列表中还有一个菜单列表对象。如何循环显示所有美食数据(新美国,日本,亚洲)。

public class RestaurantList {

    @SerializedName("restaurant_id")
    @Expose
    private String restaurantId;
    @SerializedName("restaurant_name")
    @Expose
    private String restaurantName;
    @SerializedName("cuisine")
    @Expose
    private List<Cuisine> cuisine = null;

    public List<Cuisine> getCuisine() {
        return cuisine;
    }

    public void setCuisine(List<Cuisine> cuisine) {
        this.cuisine = cuisine;
    }
}

在餐厅RVAdapter中,onBindViewHolder();

List<RestaurantList> mRestaurantList;

            List<Cuisine> cuisineList = restaurantList.getCuisine();
            String strCuisine = "";
            for (int i = 0; i < cuisineList.size(); i++) {
                strCuisine.concat(cuisineList.get(i).getCuisineName());
                strCuisine.concat(",");
                Log.i("Cuisine", cuisineList.get(i).getCuisineName());
                holder.tv_restaurant_cuisine.setText(" " + cuisineList.get(i).getCuisineName());
            }

Json Array;

[
  {...},
  {
    "restaurant_id": "41",
    "restaurant_name": "Shwe Lar Food Restaurant",
    "cuisine": [
      {
        "cuisine_name": "New American"
      },
      {
        "cuisine_name": "Japanese"
      },
      {
        "cuisine_name": "Asia"
      }
    ],
  }
]

1 个答案:

答案 0 :(得分:2)

使用以下方法解析您的数据: 我在数组和{...}

之后删除了最后一个
 private void parseJson(String jsonDataResponse){
        try
        {
            JSONArray jsonArray = new JSONArray(jsonDataResponse);

            for(int i=0;i<jsonArray.length();i++)
            {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String restaurant_id = jsonObject1.optString("restaurant_id");
                String restaurant_name = jsonObject1.optString("restaurant_name");

                JSONArray jsonArray1 =jsonObject1.getJSONArray("cuisine");

                System.out.println("restaurant_id="+restaurant_id);
                System.out.println("restaurant_name="+restaurant_name);

                for(int j=0;j<jsonArray1.length();j++)
                {
                    JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
                    String cuisine_name = jsonObject2.optString("cuisine_name");
                    System.out.println("cuisine_name="+cuisine_name);
                }
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }