12

I am hitting a service and sometimes getting back something like this:

{ "param1": "value1", "param2": "value2" }

and sometimes getting return like this:

[{ "param1": "value1", "param2": "value2" },{ "param1": "value1", "param2": "value2" }]

How do I tell which I'm getting? Both of them evaluate to a String when I do getClass() but if I try to do this:

json = (JSONObject) new JSONParser().parse(result); 

on the second case I get an exception

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

How to avoid this? I would just like to know how to check which I'm getting back. (The first case will sometimes have [] in it so I can't do index of and I'd like a cleaner way than just checking the first character.

There has got to be some sort of method that checks this?

2
  • It should be pretty simple to check if the string begins and ends with []. What have you tried? Commented May 7, 2013 at 2:46
  • I can tell if it beings and ends with [] but then the problem is that i get a string "[{\"param1\"...},{...}]" that I can't seem to convert into an array again. Commented May 7, 2013 at 3:21

2 Answers 2

25

Simple Java:

Object obj = new JSONParser().parse(result); 
if (obj instanceof JSONObject) {
    JSONObject jo = (JSONObject) obj;
} else {
    JSONArray ja = (JSONArray) obj;
}

You could also test if the (purported) JSON starts with a [ or a { if you wanted to avoid the overhead of parsing the wrong kind of JSON. But be careful with leading whitespace.


For what it is worth, an API that returns either a JSON object or an array of JSON objects depending on the result set size is ... badly designed. It would be better to always return a JSON array; e.g. an array containing zero, one or many objects. That avoids the client-side messiness we are having to deal with in this question.

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

1 Comment

Thanks. That answered my question. Now to figure out the rest of it :)
1

Though it's similar to above one, but their is not default constructor of JSONParser. Error coming was: The constructor JSONParser() is undefined

Use this instead

JsonElement jsonElement = new JsonParser().parse(jsonString);
if (jsonElement.isJsonArray()) {
    //Your Code
} else {
    //Your Code
}

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.