0

我有以下代码:

try {
    JSONObject json = new JSONObject(data);
    ...
} catch(JSONException ex) {
    if(LOGS_ON) Log.e(TAG, "Could not save data.", ex);
}

尽管传入的 json 字符串非常有效,但它会引发异常。例外情况如下:

org.json.JSONException: Value {"ShopId3Digit":"ww0","ServerTime":1426695017191,"SMSTelephone":"2104851130","SendPODAgain":true,"SendLocationAgain":true,"IsHUB":false,"AllowReceiptsAndDeliveries":true} of type java.lang.String cannot be converted to JSONObject

你看到我传入的 json 数据有问题吗?

顺便说一句,这是在 Eclipse 手表中看到的字符串:

"{\"ShopId3Digit\":\"ww0\",\"ServerTime\":1426695017191,\"SMSTelephone\":\"2104851130\",\"SendPODAgain\":true,\"SendLocationAgain\":true,\"IsHUB\":false,\"AllowReceiptsAndDeliveries\":true}"
4

2 回答 2

1

这是一个工作版本

import org.json.JSONException;
import org.json.JSONObject;

public class Test {
  public static void main(String[] args) {
    String data = "{\"ShopId3Digit\":\"ww0\",\"ServerTime\":1426695017191,\"SMSTelephone\":\"2104851130\",\"SendPODAgain\":true,\"SendLocationAgain\":true,\"IsHUB\":false,\"AllowReceiptsAndDeliveries\":true}";

    try {
      JSONObject json = new JSONObject(data);
      System.out.println("Success: json = ");
      System.out.println(json.toString(2));
    } catch(JSONException ex) {
      System.out.println("Error: " + ex);
    }
  }   
}

(使用https://github.com/douglascrockford/JSON-java提供的最新版本)。我已经测试了这段代码,它编译并成功输出

Success: json = 
{
  "IsHUB": false,
  "SMSTelephone": "2104851130",
  "AllowReceiptsAndDeliveries": true,
  "SendPODAgain": true,
  "SendLocationAgain": true,
  "ShopId3Digit": "ww0",
  "ServerTime": 1426695017191
}

因此,错误似乎与 json 数据无关。

于 2015-03-18T16:54:13.300 回答
0

毕竟是我的错。我通过 Newtonsoft 序列化程序从 .NET 程序中获取数据。我错误地序列化了已经序列化的对象,结果只是一个字符串。Eclipse 中手表中的开始和结束引号实际上是值的一部分。

感谢波尔卡教父所付出的努力。

于 2015-03-19T09:47:06.900 回答