【问题标题】:Json object getting unecessary elements?Json 对象获取不必要的元素?
【发布时间】:2017-09-19 14:15:23
【问题描述】:

我得到了这种 json 输出:

{"OrderSummary":"[
        {\"ProductQuantity\":\"1\",
        \"ProductName\":\"Wine\",
        \"Sellerid\":\"2\",
        \"ProductCost\":\"500\"}
        ,

       {\"ProductQuantity\":\"1\",
       \"ProductName\":\"Whisky\",
        \"Sellerid\":\"1\",
       \"ProductCost\":\"500\"
       }
   ]"
}

我想要这种输出

{"Order Summary":
    [

      {
         "ProductQuantity":"1",
         "ProductName":"Wine",
         "Sellerid":"2",
         "ProductPrice":"500",
         "ProductCost":"500"     
      },
      {
        "ProductQuantity":"1",
        "ProductName":"Whisky",
        "Sellerid":"2",
        "ProductPrice":"200",
        "ProductCost":"200"
      }
    ]}

这是我在获取json数组和json对象时的代码

 Cursor cursor = dbHelper.getCarProducts();
        cursor.moveToFirst();
        do {
            JSONObject product = new JSONObject();
            try {
                product.put("Sellerid",cursor.getString(cursor.getColumnIndex("_Sellerid")));
                product.put("ProductCost",cursor.getString(cursor.getColumnIndex("_Cost")));
                product.put("ProductQuantity",cursor.getString(cursor.getColumnIndex("_Quantity")));
                product.put("ProductPrice",cursor.getString(cursor.getColumnIndex("_Price")));
                product.put("ProductName",cursor.getString(cursor.getColumnIndex("_Name")));
                userCart.put(product);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }while(cursor.moveToNext());
             Cart = new JSONObject();
          try
          {
              Cart.put("OrderSummary",userCart.toString());
          }
          catch (Exception ex){ }

谁能告诉我哪里出错了?

我没有看到这种输出,我无法找到它的原因?

【问题讨论】:

  • 这在我看来就像你想要的 json 的字符串表示形式。

标签: android json sqlite


【解决方案1】:

终于经过一周的搜索、敲头、测试和尝试不同的代码,我终于找到了问题的答案和问题的原因

原因: 为了避免额外的 ""(反逗号),json 系统会放置这些正斜杠。 解决办法: 为了避免由于这些正斜杠而出错,我们可以使用 php 提供的 stripslashes() 函数(从 5.4 版开始)

以下 php 代码可以真正帮助转换生成的 json 结果:-

$jsonstring={"Order Summary":
[ 
   {
     \ "ProductName\":\"Wine\",
      \"ProductPrice\":\"500\",
      \"ProductQuantity\":\"2\",
      \"ProductCost\":\"1000\",
      \"SellerId\":\"2\"

   },
   {
      \"ProductName\":\"Whiskey\",
      \"ProductPrice\":\"1000\",
      \"ProductQuantity\":\"1\",
      \"ProductCost\":\"1000\",
      \"SellerId\":\"1\"

   }
]}
$jsondata=json_decode(stripslashes($jsonstring),true);
print_r($jsondata); 

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多