我有一個使用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"));
不要擔心Widget
或WidgetService
:這個問題與我如何使用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」的值。那麼爲什麼我會得到異常?
將訂單不直接鏈接到響應對象,這是另一個對象中 – epoch