【问题标题】:android:json object giving errorandroid:json 对象给出错误
【发布时间】:2017-10-01 12:49:59
【问题描述】:

我想使用retrofit 2 向服务器发送JSONObject,我正在发送这种json 对象:

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

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

   }
]"}

由于我无法解析 json 对象

这是我使用的源代码:-

private void loadCart()
    {


        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)
          {}}

谁能告诉我如何纠正这个错误?

【问题讨论】:

    标签: android json rest retrofit2


    【解决方案1】:

    这是你的错误

     Cart.put("OrderSummary", userCart.toString());
    

    您得到的是纯 JSON 数组,但为什么要将其转换为字符串?

    使用,

     Cart.put("OrderSummary", userCart);  // remove .toString()
    

    编辑

    通过检查您的服务器端代码,我认为问题出在index.php 文件中(我不是 PHP 专家)

    $requestedData = $response->getBody();
    

    您应该使用 $request 对象,而不是 $response。为了解决这个问题,请参阅 StackOverflow thread 或参阅 Slim Framework 的 official doc

    并从 Slim 框架发送 JSON 响应以引用此 StackOverflow thread

    注意:在声明 Java 变量/对象时,请尽量遵守 Java 变量/方法命名约定。而不是Cart 使用cart,这消除了歧义。

    【讨论】:

    • 我已经厌倦了这两种情况,在这两种情况下我得到相同的输出,所以请给我一个可行的解决方案
    • 您是否删除了.toString() 方法。我的解决方案应该有效。根据您的最终 JSON,问题是 .toString() 方法。删除后,只需重建项目并重试。你能详细说明due to which i'm unable to parse the json object 吗?你想在哪里解析它?
    • 是的,我已经删除了 to 字符串并尝试将数据发送到服务器,但它没有帮助我
    • 您的 Android 应用程序中有任何错误/日志吗?您在服务器 PHP、JAVA、C# 或其他方面使用哪种技术?请求是否从 Android 成功命中服务器?
    • 我在服务器上使用 php,是的,它成功地访问了服务器,因为它返回了一个错误
    猜你喜欢
    • 2022-10-31
    • 2012-07-08
    • 1970-01-01
    • 2021-04-18
    • 2018-03-28
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多