0

If I have a Json array object that looks like this:

[
    {"values here"},
    {"values here"},
    {"values here"}
]

And I want a Json array object that looks like this:

    {
        "key1":"value1","key2":"value2","key3":"value3"
         :[
             {"values here"},
             {"values here"},
             {"values here"}
          ]
    }

Is it possible for me to insert another json object at the front of all the elements in the array and encloses them.

  • Go this this [Nice Qusetion][1] you'll get your answer. i hope [1]: http://stackoverflow.com/questions/17810044/android-create-json-array-and-json-object – Ashfaque Mar 31 '14 at 13:41

2 Answers2

0

I'm not sure what you mean by "encloses".

You can have the first element of the array be your object.

[
   {
     "key1": "value1",
     "key2": "value2",
     "key3": "value3"
   },
   "values here",
   "values here",
   "values here"
]   

You can also have an object like

{
   "first": {
     "key1": "value1",
     "key2": "value2",
     "key3": "value3"
   },
   "rest": [
     "values here",
     "values here",
     "values here"
   ]
}
Vlad
  • 18,195
  • 4
  • 41
  • 71
  • I would like the object : "key1":"value1","key2":"value2","key3":"value3" to be the first element, then everything else inside that. –  Mar 31 '14 at 13:47
  • If it's "inside" the object, then the object needs to have a `"key4"` containing the array with the rest of the values. If the object only has three keys, you cannot have any other values inside it. – Vlad Mar 31 '14 at 13:49
0

Use the following Example

JSONObject student1 = new JSONObject();
try {
  student1.put("id", "3");
  student1.put("name", "NAME OF STUDENT");
  student1.put("year", "3rd");
  student1.put("curriculum", "Arts");
  student1.put("birthday", "5/5/1993");

} catch (JSONException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

JSONObject student2 = new JSONObject();
try {
  student2.put("id", "2");
  student2.put("name", "NAME OF STUDENT2");
  student2.put("year", "4rd");
  student2.put("curriculum", "scicence");
  student2.put("birthday", "5/5/1993");

} catch (JSONException e) {
// TODO Auto-generated catch block
  e.printStackTrace();
}


JSONArray jsonArray = new JSONArray();

jsonArray.put(student1);
jsonArray.put(student2);

JSONObject studentsObj = new JSONObject();
studentsObj.put("Students", jsonArray);



String jsonStr = studentsObj.toString();

System.out.println("jsonString: "+jsonStr);

above Example taken from Here

Community
  • 1
  • 1
Ashfaque
  • 1,254
  • 1
  • 22
  • 38