0

I have the following code that uses 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"));

Don't worry about Widget or WidgetService: this question has to do with how I'm using the Java JSON API (and specifically JSONObject).

When I run the above code, I get:

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)

As you can see, there is an order_id String field coming back in the response, and it has a value of "243050". So why am I getting the exception?

1
  • the orderid is not directly linked to the response object, it is within another object Commented Jan 27, 2014 at 14:15

2 Answers 2

2

Your JSONObject response points to the outer json object.

I am pretty sure, your response object has a property "response" (and "opstat" btw.) containing your expected object.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Max Fichtelmann (+1) - so what do I need to do to fix it?
JSONObject#getJSONObject(String) should get the inner response Object, just like @dstronczak said.
0

You have to do it like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.