0

i am using the org.json package in Java (Android) and I am just stumbled with a simple problem.

The webserver returns an array if everything is okay, but an json object { error : true, ...} if something went wrong.

How can I parse that into a common object - I mean both arrays and objects are json after all, but it seems JSONArray and JSONOBject don't share an interface in common.

Am I missing something?

2 Answers 2

2

Use JSONTokener.nextValue() and check if the result is a JSONObject or a JSONArray (using instanceof).

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

1 Comment

Nice, didn't know that class.
1

The real answer is ... fix the webserver and have it return a consistant result. Otherwise, you basically are going to have to manually inspect the returned data to see what it is.

Another option is catching the JSONException the constructor for JSONArray will throw when it isn't an array which would indicate to you that you should try JSONObject.

2 Comments

i worked with jquery a lot before, so that was never a problem, and i think as long as the server returns proper json, then this is okay.
It's "ok" in that it is valid JSON. From a design perspective it's poor, which is precisely why you've having to jump through hoops in a language that isn't dynamically typed (and even in one that is you are still dealing with two different types). If an object was returned an object in both cases, these problems go away.

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.