Videos
The difference between an array and an object is that
Objects are set up using a key and value like:
person.age = 15;
If the key value is a variable, then one could access it like:
var key = "age";
alert(person[key]);
Arrays use an integer[1] index and take a value.
player[1].score += 1000;
[1] Yes, I know, in JavaScript the integer index is really turned into a string behind the scenes. Ignore that. Think of arrays taking an integer value ESPECIALLY when you think of JSON.
Objects- key and value, Arrays- integer. When do you use this or that?
I think of arrays and objects as "is a/an" and "has a" respectively. Lets use "Fruit" as example.
Every item in fruit array is a type of fruit.
array fruit : [orange, mango, banana]
. Arrays can contain objects,strings, numbers, arrays, but lets deal with only objects and arrays.
array fruit : [orange:[], mango:{}, banana:{}]
. You can see that orange is an array too. It implies any item that goes int orange is a type of orange, say: bitter_orange, mandarin, sweet_orange.
for fruit object, any item in it is an attribute of fruit. thus the fruit has a
object fruit :{seed:{}, endocarp:{},flesh:{}}
This also implies that anything within the seed object should be property of seed, say: colour,
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 that returns a JSON object containing some metadata alongside an array of the items matching your query:
{"startIndex": 0, "data": [{"name": "item 1"},{"name": "item2"} ]}
The difference is the same as a (Hash)Map vs List.
JSONObject:
- Contains named values (key->value pairs, tuples or whatever you want to call them)
- like
{ID : 1}
- like
- Order of elements is not important
- a JSONObject of
{id: 1, name: 'B'}is equal to{name: 'B', id: 1}.
- a JSONObject of
JSONArray:
- Contains only series values
- like
[1, 'value']
- like
- Order of values is important
- array of
[1,'value']is not the same as['value',1]
- array of
Example
JSON Object --> { "":""}
JSON Array --> [ , , , ]
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}