137

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.

0

6 Answers 6

265

org.json.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"}
Sign up to request clarification or add additional context in comments.

4 Comments

How do I convert it back to a JSONObject from a string?
JSONObject jsonObj = new JSONObject("your_json_string");
FYI that this will fail to parse JSON arrays (even though they are technically valid JSON). For example, trying JSONObject("[{\"foo\":2, \"bar\": 3}]"); results in A JSONObject text must begin with '{' at 1 [character 2 line 1]
JSONArray uses the "add" rather than the "put" method. Change array.put(item); to array.add(item);
13

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)

Comments

4

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)

1 Comment

updated code that worked for me import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class Main { public static void main(String[] args) { String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"; JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString); // Print the parsed JsonObject System.out.println(jsonObject); } }
3
 String jsonString = "{'element1':'value1','element2':{'id':0,'name':'testName'}}";
        JsonObject jsonObject = (JsonObject) JsonParser.parseString(jsonString);

Comments

1

Underscore-java can create json from an object.

import com.github.underscore.U;

    String message = U.objectBuilder()
            .add("course", U.arrayBuilder()
                    .add(U.objectBuilder()
                            .add("id", 3)
                            .add("information", "test")
                            .add("name", "course1")
                    ))
            .add("name", "student")
            .toJson();
    System.out.println(message);

// {
//   "course": [
//     {
//       "id": 3,
//       "information": "test",
//       "name": "course1"
//     }
//   ],
//   "name": "student"
// }

Comments

0

Code that worked for me

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

public class Main {
    public static void main(String[] args) {
        String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}";
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString);

        // Print the parsed JsonObject
        System.out.println(jsonObject);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.