Java 如何使用字符串创建 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20117148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:15:37  来源:igfitidea点击:

How to create JSON Object using String?

javaandroidjson

提问by ravi

I want to create a JSON Object using String.

我想使用字符串创建一个 JSON 对象。

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

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

In order to create the above JSON I am using this.

为了创建上述 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);

I want to know how can I create a JSON which has JSON Array in it.

我想知道如何创建一个包含 JSON 数组的 JSON。

Below is the sample 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,
    }
  ]
}

Thanks.

谢谢。

采纳答案by srain

JSONArraymay be what you want.

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

回答by Walter Palacios

In contrast to what the accepted answer proposes, the documentation says that for JSONArray()you must use put(value)no add(value).

与接受的答案建议相反,文档说对于JSONArray()你必须使用put(value)no add(value)

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

(Android API 19-27. Kotlin 1.2.50)

(Android API 19-27。Kotlin 1.2.50)