如何使用String创建JSON对象?


91

我想使用String创建一个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,
    }
  ]
}

谢谢。

Answers:


182

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

如何将其JSONObject从字符串转换回a?
morha13 '18

JSONObject jsonObj = new JSONObject("your_json_string");
卡米尔

仅供参考,这将无法解析JSON数组(即使它们在技术上是有效的JSON)。例如,尝试JSONObject("[{\"foo\":2, \"bar\": 3}]");导致A JSONObject text must begin with '{' at 1 [character 2 line 1]
user2490003

1
像魅力一样运作
Sobhit Sharma


0

如果您使用gson.JsonObject,则可以得到以下内容:

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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.