Json拼接

java 复制代码
package service.WebWh;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class a {

    public static void main(String[] args) {

        // 创建一个 JSONArray 对象用于存储多个 JSON 数据对象
        JSONArray jsons = new JSONArray();

        // 创建第一个 JSON 数据对象并添加数据
        JSONObject data1 = new JSONObject();
        data1.put("name", "张三");   // 添加姓名字段
        data1.put("age", 25);        // 添加年龄字段
        data1.put("gender", "男");   // 添加性别字段
        jsons.add(data1);            // 将第一个数据对象添加到 JSONArray 中

        // 创建第二个 JSON 数据对象并添加数据
        JSONObject data2 = new JSONObject();
        data2.put("name", "李四");   // 添加姓名字段
        data2.put("age", 30);        // 添加年龄字段
        data2.put("gender", "男");   // 添加性别字段
        jsons.add(data2);            // 将第二个数据对象添加到 JSONArray 中

        // 创建最终的 JSON 数据对象
        JSONObject json = new JSONObject();
        json.put("code", 0);         // 添加状态码字段,表示成功
        json.put("msg", "成功");     // 添加消息字段,表示成功
        json.put("count", "2");      // 添加数据数量字段,表示数据中包含两个对象
        json.put("data", jsons);     // 添加数据字段,将 JSONArray 对象作为值

        // 打印最终生成的 JSON 字符串
        System.out.println(json.toJSONString());

    }
}

json打印结果

java 复制代码
{
  "code": 0,
  "msg": "成功",
  "count": "2",
  "data": [
    {
      "name": "张三",
      "age": 25,
      "gender": "男"
    },
    {
      "name": "李四",
      "age": 30,
      "gender": "男"
    }
  ]
}
相关推荐
曲幽5 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805110 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon11 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly11 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程11 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly13 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风20 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风20 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python