gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:53:13 25 4
gpt4 key购买 nike

我想用字符串创建一个 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,
}
]
}

谢谢。

最佳答案

org.json.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.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

关于java - 如何使用字符串创建 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20117148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com