Как создать объект JSON с помощью String?
Я хочу создать объект JSON с помощью String.
Пример:
JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}
Чтобы создать вышеупомянутый JSON, я использую это.
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);
message = json.toString();
System.out.println(message);
Я хочу знать, как создать JSON с массивом JSON в нем.
Ниже приведен образец JSON.
{
"name": "student",
"stu": {
"id": 0,
"batch": "[email protected]"
},
"course": [
{
"information": "test",
"id": "3",
"name": "course1"
}
],
"studentAddress": [
{
"additionalinfo": "test info",
"Address": [
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":36
}
],
"verified": true,
}
]
}
Спасибо.
Ответы
Ответ 1
JSONArray
может быть тем, что вы хотите.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}