tags:

views:

44

answers:

3

I'm new to JSON.

I need to receive a response (in form of a String) from a server. That response can be an object like

{"a" : "value", "b" : "value2", ...}

if the request was successful, or a single string like

"ERROR"

on error.

Using org.json.JSONObject, how do I check which one has been returned?


EDIT

I think this could work, but I'm not sure if this is the right way to do it

if(JSONString.equals("\"ERROR\"") {
    //handle error
} else {
    //parse actual object
}

Where JSONString is a String containing the server response

Could this work?

+1  A: 

The string "ERROR" is not valid JSON. Look at the JSONWriter API and you will see there is no way to produce a JSON string like "ERROR".

If you always want to treat the server response as json, you will need to have it return something like { "error" : true } or { error : false }. Your program will then be able to deserialize check the error field.

If you don't have control on the server response, then you will need to test String.equals("ERROR") before deserializing.

Philippe A.
I can't change the way the server responds. It's a third party service.
klez
Then you will need to test String.equals("ERROR") before deserializing.
Philippe A.
Please move your comment to your answer. I'm accepting it, but it would be tidier if you move it there.
klez
A: 

Since you can't make the third party service output valid json, before you do json parsing, just do a string comparison to see if the response is "error".

hvgotcodes
A: 

A quoted string is a valid json value in my opinion. The grammar at json.org does not define object or array as special topleve productions, rfc 4627 defines json-text as being an object or array, but a json value can also be a number, string, boolean or null.

From my reading of the org.json javadoc the following should work:

Object value = new JSONTokener(inputString).nextValue();
if (value instanceof String && ((String)value).equals("ERROR")) {
    // handle error
} else if (value instanceof JSONObject) {
    // handle response data
}

Using the tokener you are not affected by eventual additional whitespace in the response.

Jörn Horstmann
I'll try tomorrow. Thanks.
klez