【问题标题】:How do I extract this json Array inside of an Array with Volley?如何使用 Volley 在数组中提取这个 json 数组?
【发布时间】:2019-06-11 22:31:36
【问题描述】:

json Image我正在尝试从 Json 对象中提取数据列表(数组),但我不知道。这是我试图提取的“成分”的价值。我试图将其提取为字符串,但它未格式化。我还提供了原始 jsonenter code here 的图像。如果我尝试将其提取为“cake.optJSONArray”,我会得到一个 java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.List 我添加了更多代码来帮助这个问题变得有意义(手指交叉我并没有让它更混乱)。

   try {

                for (int i = 0; i < response.length(); i++) {
                    JSONObject cake = response.getJSONObject(i);

                    String cakeId = cake.optString("id");
                    String cakeName = cake.optString("name");


                    List<Ingredients> ingredients = (List<Ingredients>) cake.optJSONArray("ingredients");

                    mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
                }

公共类 CakesItem {

private String mId;
private List<Ingredients> mIngredients;
private String mName;

public CakesItem(String cakeId, Lists <Ingrediets> ingredients String cakeName) {
    mId = cakeId;
    mIngredients = ingredients;
    mName = cakeName;

}

公共类成分实现 Parcelable {

private double quantity;
private String measure, ingredient;


public Ingredients() {
}

【问题讨论】:

    标签: android json android-volley


    【解决方案1】:

    我不确定您使用的是什么 JSON 库,但是如果您导入 org.json.JSONArray,那么如果您的蛋糕是您从 Volley 返回的 JSONObject 响应中获得的 org.json.JSONObject,您会使用这个语法:

    JSONObject cake = response.getJSONObject(i);
    JSONArray ingredients = cake.getJSONArray("ingredients");
    

    然后,由您将 JSONArray 成分中的值放入您的列表中。它看起来像这样:

    for (int i = 0; i < response.length(); i++) {
        JSONObject cake = response.getJSONObject(i);
    
        String cakeId = cake.optString("id");
        String cakeName = cake.optString("name");
    
        JSONArray JSONingredients = cake.optJSONArray("ingredients");
    
        List<Ingredients> ingredients = new List<Ingredients>();
    
        for (int j = 0; j < JSONingredients.length(); j++) {
            JSONObject item = JSONingredients.getObject(j);
    
            String measure = item.getString(“measure”);
            String ingredient = item.getString(“ingredient”);
            Double quantity = item.getDouble(“quantity”);
    
            Ingredients item2 = new Ingredients(measure, ingredient, quantity);
            ingredients.add(item2);
          } 
    
    
          mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
        }
    

    【讨论】:

    • 哦,是的,这是可行的,但它仍然会产生未格式化的文本,因为 JSONArray(“成分”)内部是一个完整的对象数组,它们是数量、度量和成分,我希望这些值这样格式化我最初创建了 2 个对象(CakeItem 和成分)
    • 谢谢你的工作,我只需要把 List 变成一个 ArrayList。
    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多