Làm thế nào để tạo Đối tượng JSON bằng Chuỗi?


91

Tôi muốn tạo một Đối tượng JSON bằng cách sử dụng Chuỗi.

Ví dụ: JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}

Để tạo JSON ở trên, tôi đang sử dụng cái này.

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

Tôi muốn biết làm thế nào tôi có thể tạo một JSON có JSON Array trong đó.

Dưới đây là JSON mẫu.

{
  "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,
    }
  ]
}

Cảm ơn.

Câu trả lời:


183

JSONArray có thể là những gì bạn muốn.

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

Làm cách nào để chuyển đổi nó trở lại thành a JSONObjecttừ một chuỗi?
— morha13

JSONObject jsonObj = new JSONObject("your_json_string");
— Camille

FYI rằng điều này sẽ không phân tích cú pháp mảng JSON (mặc dù chúng là JSON hợp lệ về mặt kỹ thuật). Ví dụ, cố JSONObject("[{\"foo\":2, \"bar\": 3}]");kết quả trongA JSONObject text must begin with '{' at 1 [character 2 line 1]
— user2490003

1
Hoạt động như một sự quyến rũ
— Sobhit Sharma


0

Nếu bạn sử dụng gson.JsonObject, bạn có thể có một cái gì đó tương tự như vậy:

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)
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookie và Chính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.