Hi I'm trying to make an alphabetised list with headers so i want an array of JSONObjects with the key of "B" for example inside that object i'm going to be adding an array of JSONObjects that contains contacts whose name begins with the key or "B"
does anyone know how to add a JSONObject to a JSONArray with a key? so that i can retrieve specific Objects
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
We can merge two JSON arrays using the addAll() method (inherited from interface java. util.
jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
To reach your requirement your JSON object should like this
{
"A":[
{
"name":"aaa"
},
{
"name":"aba"
}
],
"B":[
{
"name":"bbb"
},
{
"name":"bba"
}
]
}
A pseudo implementation for above Object would look like this:
//Maint list object
JSONObject objMainList = new JSONObject();
//prepare item array for "A"
JSONArray arrForA = new JSONArray();
JSONObject itemA = new JSONObject();
itemA.put("name", "aaa");
arrForA.put(itemA);
//prepare item array for "B"
JSONArray arrForB = new JSONArray();
JSONObject itemB = new JSONObject();
itemB.put("name", "bbb");
arrForB.put(itemB);
//Finally add item arrays for "A" and "B" to main list with key
objMainList.put("A", arrForA);
objMainList.put("B", arrForB);
UPDATE : to check if "A" or "B".. is exists or not
if(objMainList.has("A")){
}
Try out this way:
{"Contacts": //JSONObject
{
"B"://JSONArray..
[
{"ContactName":sdfsdf,"ID":900,"Number":1368349},
{"ContactName":adsdfd,"ID":1900,"Number":136856},
{"ContactName":adglkhdofg,"ID":600,"Number":136845}
],
"C":[
{"ContactName":alkghoi,"ID":900,"Number":1368349},
{"ContactName":wetete,"ID":1900,"Number":136856},
{"ContactName":dfhtfh,"ID":600,"Number":136845}
]
.....//and so on..
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With