-1

I have a JSONObject. I need to append some details to that.

Existing JSON

{
"class": {
    "name": "first",
    "language": "English"
  }
}

and i need to append values to this like

{
"class": [{
    "name": "first",
    "language": "English"
}, {
    "name": "first",
    "language": "English"
}]
}
Arya
  • 1,729
  • 3
  • 17
  • 35
  • Create `JsonArray`, put `JsonObject`s which contains strings "name" and "language", and finally put array named "class" into first jsonobject. – grabarz121 Dec 17 '20 at 08:36

2 Answers2

0

I'm not the first to ever say this, But you should use JSONObject.put with the modified value, e.g

JSONObject main = new JSONObject();
// ...
main.put("Classes", newClasses);
A. Abramov
  • 1,823
  • 17
  • 45
0

You can't do that with your current object. You have to change the type of the JSONObject you're appending to. As noted in the comments, you actually just want to serialize an array of custom objects.

Therefore, create a JsonArray as described in this answer: JSONObject.append into object - result is nested array?

Java is not my first language, but maybe this will help you out:

//First create the name and language object
JSONObject nameLanguageObj = new JSONObject();
nameLanguageObj.add("name","first");
nameLanguageObj.add("language","English");

//Create the array to hold the objects
JSONArray arr = new JSONArray();
arr.put(nameLanguage);

//Create the full class object as you requested.
JSONObject classObj = new JSONObject();
classObj.put("class", arr);
Zimano
  • 1,870
  • 2
  • 23
  • 41