如何从深层嵌套的json数组中获取json对象数组?

时间:2017-06-07 12:54:40

标签: android json sqlite android-recyclerview retrofit

这是我的json,我想得到'产品'数组对象。

{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }

我可以像这样在我的数据库中保存类别。

  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }

这是一个分类模型类:

public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}

我正在使用改造库来获取数据。这是我用来在db中保存类别数组的方法。

@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}

但是如何从类别中获取产品jsonArray。尝试了很多,但无法找到方法。非常感谢您的帮助。需要在类别的基础上获得产品。请帮助。提前谢谢。

Ashish我正在使用你的方法:

 private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }

4 个答案:

答案 0 :(得分:1)

JSONArray array = object.optJSONArray("Categories");  // first get your Categories array from Json Object.

 // Then iterate your categories array.
for (int i = 0; i <array.length ; i++)
    {
        JSONObject innerObject = array.getJSONObject(i);     // get inner json object from array.
        JSONArray innerArray = object.optJSONArray("product");       // then get product array from inner json object
    }

答案 1 :(得分:1)

1)如果已创建已更新为String,则已删除字符串。

2)假设Person很好地反映了json结构,Pivot的类也是如此,为了获得产品,你可以这样做:

ArrayList<Category> categories = getAllCategories();
for(Category category : categories){
    for(Product product : category.getProduct()){
         <Do something with each product of the category >
    }
}

3)在类别中,获取产品列表的更好名称是getPrduct s ()而不是getProduct()。

编辑1

按产品名称搜索:

缓慢的方式:

这会遍历所有类别,直到找到与productName匹配的产品。如果有多个,则返回第一个。

Product getProductByName(String productName){
        Product rtn = null;
        ArrayList<Category> categories = getAllCategories();
        for(Category category : categories){
            for(Product product : category.getProduct()){

                 if(product.getName().equals(productName){
                    rtn = product;
                    break;
                 }
            }
        }
        return rtn;
}

您可以采取不同的方法来更快地进行搜索:

1)不是存储json字符串,而是打开不同的对象并将信息放在不同的表中:categoris,products,pivot。

2)构建某种索引,你可以为每个产品保留json字符串,类别的id和产品的id。当您需要产品时,可以在索引中查找并阅读提取产品所需的特定记录。

3)一种缓存策略,它将慢速查找与hashmap中的索引相结合。

你可以做更多的事情,这是提供一些想法。

编辑2

按类别名称的产品:

ArrayList<Product> getProductsByCategoryName(String categoryName){
    ArrayList<Product> rtn = new ArrayList<>();
    ArrayList<Category> categories = getAllCategories();
    for(Category category : categories){
        if(category.getName().equals(categoryName){
           rtn = category.getProduct();
        }
    }
    return rtn;
}

答案 2 :(得分:1)

步骤1)使用gson属性进行回复.. http://www.jsonschema2pojo.org/将有助于制作gson类。

  

youSource类型:JSON,注释样式:GSON并添加getter setter   方法

步骤2)现在你拥有了所有带有gson注释的类。

步骤3)现在json

 Gson gson = new GsonBuilder().create();
 JSONArray mainData = response.getJSONArray("Categories");
 ArrayList<YourMasterClass> responseAsArrayList = 
                      gson.fromJson(mainData.toString(), new TypeToken<List<YourMasterClass>>() {
                    }.getType());

步骤4)在获得arraylist中的所有数据后,您的逻辑就会正常运行。

  

这里我只是假设arraylist名称,所以请替换你的gson类。

for(int i =0;i<responseAsArrayList.size();i++)
{
      for(int j = 0; responseAsArrayList.get(i).getProductArray().size();j++)
      {
          // Here you will get your Product object
      }

}

答案 3 :(得分:0)

json.getJSONArray(&#34;关键字&#34)。getJSONObject(0).getJSONArray(&#34;产品&#34)

会给你产品数组