0

I have a JSON array which I receive from a HTTP request :

[
  '{{repeat(5, 7)}}',
  {
    _id: '{{objectId()}}'
  }
]

At times I receive only a simply JSON object and not an array.

How do I generalize and store the response, since sometimes I get as an array and sometimes as a normal JSON object.

Currently I have done it this way: JSONObject j = new JSONObject(recvdString);

In the case of JSON array I get an error: A JSONObject text must begin with '{' at character 1 of

user1692342
  • 5,007
  • 11
  • 69
  • 128
  • what library are you using? – Peter Gelderbloem Nov 09 '16 at 15:16
  • @PeterGelderbloem Jettison – user1692342 Nov 09 '16 at 15:17
  • if the json object you're getting is of the same type of the elements in the json array you're getting otherwise, you can just put the object in an array (you can determine if it's an object or an array as explained [here](http://stackoverflow.com/questions/9988287/test-if-it-is-jsonobject-or-jsonarray)) – dabadaba Nov 09 '16 at 15:19
  • If not problematic, treat a JSON response as a JSON array of 1 element, i.e your first job is to treat the response as an array no matter what and go from there – Mechkov Nov 09 '16 at 15:19
  • possible duplicate of [how-to-tell-if-return-is-jsonobject-or-jsonarray](http://stackoverflow.com/questions/16410421/how-to-tell-if-return-is-jsonobject-or-jsonarray-with-json-simple-java) – D Ie Nov 09 '16 at 15:23

1 Answers1

0

Is not a valid json. This one should run:

[
  "{{repeat(5, 7)}}",
  {
    "_id": "{{objectId()}}"
  }
]

However you can validate your json in a usefull services online like this

Andrea Cip
  • 41
  • 4