[java] How to create JSON Object using String?

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.

This question is related to java android json

The answer is


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"}

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)


If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?