Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON Object using String?

Tags:

java

json

android

I want to create a JSON Object using String.

Example : JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}

In order to create the above JSON I am using this.

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); 

I want to know how can I create a JSON which has JSON Array in it.

Below is the sample JSON.

{   "name": "student",    "stu": {     "id": 0,     "batch": "batch@"   },   "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,     }   ] } 

Thanks.

like image 737
ravi Avatar asked Nov 21 '13 09:11

ravi


People also ask

How do you create a JSON object?

String message; JSONObject json = new JSONObject(); json. put("test1", "value1"); JSONObject jsonObj = new JSONObject(); jsonObj. put("id", 0); jsonObj. put("name", "testName"); json.

How do I create a JSON file from a text file?

Open a Text editor like Notepad, Visual Studio Code, Sublime, or your favorite one. Copy and Paste below JSON data in Text Editor or create your own base on the What is JSON article. Once file data are validated, save the file with the extension of . json, and now you know how to create the Valid JSON document.


2 Answers

JSONArray may be what you want.

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"} 
like image 61
srain Avatar answered Sep 24 '22 12:09

srain


In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

(Android API 19-27. Kotlin 1.2.50)

like image 29
Walter Palacios Avatar answered Sep 22 '22 12:09

Walter Palacios