1

I am getting a JSON string back from my server, which can be either a JSONArray or a JSONObject, and I do not know beforehand what I'll get (at least not in that part of the code).

Is there a way to handle this? My first guess would be to do something like this:

if (jsonString.startsWith("[")) {
   r = new JSONArray(jsonString);
} else {
   r = new JSONObject(jsonString);
}

but this feels a little 'hackish'.

Tim
  • 41,901
  • 18
  • 127
  • 145
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • 1
    If possible, talk to the server dev about making the response always an object or always an array – Tim Sep 14 '17 at 14:38
  • 1
    The server returning two different answers is already a bit hackish. Agree with @TimCastelijns, the cleanest way is changing the server. – Xavier Rubio Jansana Sep 14 '17 at 14:39
  • @TimCastelijns luckily, I am the server dev, but I didn't want to touch the interface just yet if there was another solution. – Bart Friederichs Sep 14 '17 at 14:39
  • 2
    there are other solutions, such as the one you presented, but none will be as "clean" as making it the server's responsibility to deliver data in a format the client can easily work with – Tim Sep 14 '17 at 14:41
  • u can refer https://stackoverflow.com/questions/16518252/different-json-array-response – Nithinlal Sep 14 '17 at 14:43
  • "at least not in that part of the code" -- isn't this the problem? Shouldn't you be passing some indication, into this part of the code, what is that you are parsing? – CommonsWare Sep 14 '17 at 14:43
  • I can't look into your current infrastructure, but I agree with Tim that it is better to change the server. If, for any reason, you have a new client to connect to that same server, you're stuck with this issue again – 0xDEADC0DE Sep 14 '17 at 14:43
  • @CommonsWare the parser is in a generic part of the code. I should just return a JSONObject back. I will change the server side and the problem just disappears. – Bart Friederichs Sep 14 '17 at 14:49

2 Answers2

2

how about instanceof with JSONTokener?

Object unknownJSON = new JSONTokener(data).nextValue();
if (unknownJSON instanceof JSONObject)
  // well, you know
else if (unknownJSON instanceof JSONArray)
  // you should also know
Yamen Nassif
  • 2,416
  • 2
  • 24
  • 48
0

Very hackish but you can try this

try {
JSONObject object = new JSONObject(jsonString);
// u received a json object
} catch (JSONException e) {
// you received a json array
JSONArray array = new JSONArray(jsonString);
}
jitinsharma
  • 1,436
  • 13
  • 22
  • I agree that this works, but it is more or less the same as what OP already did with the if statement. Only problem with this would be that if you don't receive JSON for any reason, the catch part will crash – 0xDEADC0DE Sep 14 '17 at 14:46
  • May be one more catch while parsing as jsonarray. There is no good way to do this on client side. – jitinsharma Sep 14 '17 at 14:48