Difference between JSONObject and JSONArray


After having a short look at Google I found this link that describes the difference, yet from a syntax point of view.

When would one be preferred over the other in a programming scenario?


When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example: [{"name":"item 1"},{"name": "item2} ]

On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item. For example: {"name": "item1", "description":"a JSON object"}

Of course, JSON arrays and objects may be nested inside one another. One common example of this is an API which returns a JSON object containing some metadata alongside an array of the items matching your query:

{"startIndex": 0, "data": [{"name":"item 1"},{"name": "item2"} ]}

Answered By – Eric Levine

Leave a Comment