2014-01-27 66 views
0

我有一个使用Java JSON下面的代码: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 API JSON做(特别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”的值。那么为什么我会得到异常?

+0

将订单不直接链接到响应对象,这是另一个对象中 – epoch

回答

2

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

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

+0

感谢@Max Fichtelmann(+1) - 还等什么,我需要要解决它吗? – AdjustingForInflation

+0

[JSONObject#getJSONObject(String)](http://www.json.org/javadoc/org/json/JSONObject.html#getJSONObject(java.lang.String))应该获得内部响应对象,就像@dstronczak说过。 –

0

你要做这样的:

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