解码JSON数组

时间:2019-06-22 09:05:36

标签: android arrays json android-recyclerview

我有一个名为“ items”的列的数据库,我将JsonString放在该列中。我想在for循环中从数组中获取数据,但它没有给我数据 这是我的代码:

dbConnector = new DbConnector(getContext(),null,null,1);

        Cursor c = dbConnector.get().rawQuery("SELECT * FROM factors",null);

        while (c.moveToNext()){
            String name = c.getString(c.getColumnIndex("name"));
            String items = c.getString(c.getColumnIndex("items"));
            String itemsEncoded = null;
            int priceEncoded = 0;
            int amount = 0;
            try {
                JSONArray mJsonArray = new JSONArray(items);
                JSONObject mJsonObject;
                Log.e("JSON ARRAY",mJsonArray.length() + "");
                for (int i = 0; i < mJsonArray.length(); i++) {
                    mJsonObject = mJsonArray.getJSONObject(i);
                    mJsonObject.getString("product_id");
                    priceEncoded += Integer.parseInt(mJsonObject.getString("price"));
                    amount       += Integer.parseInt(mJsonObject.getString("number"));
                    itemsEncoded += mJsonObject.getString("product_name") + " - " + mJsonObject.getString("price") + " ????? " + " - " + mJsonObject.getString("number")+ " ???" + "\n";
                }
            }catch (JSONException e){
                Log.e("ERROR",e.getMessage());
            }

            list.add(new FactorObject(name,priceEncoded + "",amount,itemsEncoded));
        }


        recyclerView = view.findViewById(R.id.factorRecycler);
        adapter = new FactorsAdapter(getContext(),list);

        recyclerView.setAdapter(adapter);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

变量“ priceEncoded”,“ amount”,“ itemsEncoded”均为空,并且似乎for循环不起作用

JSON示例: JSON Example

我也100%确信我的数据库已满

1 个答案:

答案 0 :(得分:1)

您的JSON不包含“ product_id”,并且mJsonObject将为null。 最好使用模型类来解码JSON,创建一个具有JSON字段的类

class JsonModelVM{
private String product_name,buyer_name;
private int number;
private double price;
  public void setProduct_name(String product_name) {
    this.product_name = product_name;
   }

public String getBuyer_name() {
    return buyer_name;
   }

public void setBuyer_name(String buyer_name) {
    this.buyer_name = buyer_name;
   }

public int getNumber() {
    return number;
   }

public void setNumber(int number) {
    this.number = number;
   }

public double getPrice() {
    return price;
   }

public void setPrice(double price) {
    this.price = price;
   }
}

并在解码类中使用Gson libray

implementation 'com.google.code.gson:gson:2.8.2'
.
. 
.
JsonModelVM object = new Gson().fromJson(mJsonArray.getJSONObject(i).toString(), 
AppCourseVM.class);

它将返回一个可以使用它的对象;)