Como criar o objecto JSON usando o texto?

quero criar um objecto JSON usando um texto.

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

para criar o JSON acima, estou a usar isto.

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);
Quero saber como posso criar um JSON que tem uma matriz JSON.

Abaixo está a amostra 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,
    }
  ]
}
Obrigado.

Author: ravi, 2013-11-21

2 answers

JSONArray talvez seja o que tu queres.

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.add(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
 112
Author: srain, 2018-07-24 16:54:38

Em contraste com o que a resposta aceita propõe,a documentação diz que para JSONArray () {[5] } você deve usar 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)
 1
Author: Walter Palacios, 2018-08-22 07:55:49