I want to create a JSON Object using String.

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

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

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 Array的JSON.

Below is the sample 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 may be what you want.

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

Json相关问答推荐

使用更高级别架构中的字段值在$def内实现约束

盒子图显示不正确

如何创建生成两个不同对象的JSON数组的SQL查询?

使用PowerShell解析文件并获取特定行的值

解析SQL中的嵌套JSON

使用JQ从jsonl文件中删除具有匹配键/值的行

jq EOF 处的无效数字文字将 json 值更新为 0.0.x

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

如何使用 jq 在连续的 json 记录流上调用操作

如何使用 SQL Server 将 json 存储为字符串的列分解/规范化为行和列?

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

向 JSON 文件添加注释

如何在 Django 的模板语言中获取 json 键和值?

Json.Net:用于自定义命名的 JsonSerializer-Attribute

将 PHP 结果数组转换为 JSON

如何自动修复无效的 JSON 字符串?

ASP.NET Core API 仅返回列表的第一个结果

如何使用 Gson 将 JSONArray 转换为 List?

设置对象不是 JSON 可序列化的

Volley JsonObjectRequest Post 参数不再起作用