Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my JSON object using String:

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

Here’s the code to create 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);

Here’s my 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,

    }

  ]

}


Can anyone tell me how to create a JSON with a JSON array in it? 

1 Answer

0 votes
by (19.7k points)

You can create the JSON array like below:

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

Interested in Java? Check out this Java tutorial by Intellipaat.  

Related questions

0 votes
1 answer
asked Apr 27, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Nov 4, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Feb 15, 2021 in Web Technology by Jake (7k points)
0 votes
1 answer

Browse Categories

...