IT박스

문자열을 사용하여 JSON 개체를 만드는 방법은 무엇입니까?

itboxs 2020. 10. 14. 07:37
반응형

문자열을 사용하여 JSON 개체를 만드는 방법은 무엇입니까?


문자열을 사용하여 JSON 개체를 만들고 싶습니다.

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

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

JSON 배열이있는 JSON을 어떻게 만들 수 있는지 알고 싶습니다.

다음은 샘플 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,
    }
  ]
}

감사.


JSONArray 당신이 원하는 것일 수 있습니다.

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

수락 된 답변이 제안하는 것과 달리 설명서에는 JSONArray ()에 대해 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)

참고 URL : https://stackoverflow.com/questions/20117148/how-to-create-json-object-using-string

반응형