繁体   English   中英

Java JSON反序列化错误

[英]Java JSON Deserialization Error

我有以下使用Java JSON的代码:

Widget w = new Widget(true, "LIVE");
WidgetService service = new WidgetServiceImpl();    // 3rd party JSON web service

JSONObject response = service.postWidget(w);

System.out.println("Response is: " + response.toString());
System.out.println("Now fetching orderid...");
System.out.println(response.getString("order_id"));

不要担心WidgetWidgetService :这个问题与我如何使用Java JSON API(特别是JSONObject )有关。

当我运行上面的代码时,我得到:

Response is: {"response":{"credits_used":"0.30","job_count":1,"order_id":"243050","currency":"USD"},"opstat":"ok"}
Now fetching orderid...
Exception in thread "main" org.json.JSONException: JSONObject["order_id"] not found.
    at org.json.JSONObject.get(JSONObject.java:473)
    at org.json.JSONObject.getString(JSONObject.java:654)
    at com.me.myapp.MyDriver.main(MyDriver.java:49)

如您所见,响应中有一个order_id字符串字段,其值为“243050”。 那么为什么我会得到例外?

您的JSONObject response指向外部json对象。

我很确定,你的响应对象有一个包含你期望对象的属性"response" (和"opstat" btw。)。

你必须这样做:

response.getJSONObject("response").getString("order_id");

暂无
暂无

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

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