简体   繁体   English

在json数组中添加json对象,在sqlite中添加json对象中的agian json数组

[英]adding json object in json array and agian json array in json object from sqlite

I m new to android i want to get json format like below 我是android的新手我希望得到如下的json格式

here is image what i want json output 这是我想要的json输出的图像

here is code 这是代码

 public JSONObject getjsondataofcart(){
    JSONObject modelList = new JSONObject();
    JSONArray myara   = new JSONArray();
    String query = "select * from "+ cart_table;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query,null);
    JSONObject data = new JSONObject();
    try {

      if (cursor.moveToFirst()) {
        do {

          data.put("id", cursor.getInt(1));
          data.put("qty", cursor.getInt(2));
          data.put("amount", cursor.getInt(7));
          data.put("tax_id","0");
          data.put("sub_total", cursor.getInt(6));
          myara.put(data);
        } while (cursor.moveToNext());

        modelList.put("product_detail",myara);
      }
    }
    catch (JSONException e)
    {
    }

    return modelList;
  }

I got out put as below: 我拿出如下:

here is what i got 这就是我得到的

any help will be appreciated. 任何帮助将不胜感激。 thanks in advanced 提前致谢

Try with below code: 试试以下代码:

 public JSONObject getjsondataofcart(){
        JSONObject modelList = new JSONObject();
        JSONArray myara   = new JSONArray();
        String query = "select * from "+ cart_table;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query,null);

        try {

            if (cursor.moveToFirst()) {
                do {
                    //Add this line here
                    JSONObject data = new JSONObject();
                    data.put("id", cursor.getInt(1));
                    data.put("qty", cursor.getInt(2));
                    data.put("amount", cursor.getInt(7));
                    data.put("tax_id","0");
                    data.put("sub_total", cursor.getInt(6));
                    myara.put(data);
                } while (cursor.moveToNext());

                modelList.put("product_detail",myara);
            }
        }
        catch (JSONException e)
        {
        }

        return modelList;
    }
JSONObject data = new JSONObject(); 

Move above line inside of do-while loop like below 如下所示在do-while循环内移动线

try {

  if (cursor.moveToFirst()) {
    do {
      JSONObject data = new JSONObject();
      data.put("id", cursor.getInt(1));
      data.put("qty", cursor.getInt(2));
      data.put("amount", cursor.getInt(7));
      data.put("tax_id","0");
      data.put("sub_total", cursor.getInt(6));
      myara.put(data);
    } while (cursor.moveToNext());

    modelList.put("product_detail",myara);
  }
}
catch (JSONException e)
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM