Jackson指定json的key

指定json的key

要在序列化JavaBean时指定JSON的key,可以使用@JsonProperty​注解来指定JavaBean属性序列化到JSON时使用的key。以下是一个简单的示例:

java 复制代码
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setId(1);
        user.setName("张三");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
    }

    public static class User {
        private int id;

        @JsonProperty("username")
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

在上面的例子中,User​类有一个属性name​,通过在该属性上使用@JsonProperty("username")​注解,我们指定了当User​对象被序列化为JSON时,name​属性对应json的key应该是username​。因此,输出的JSON字符串中,原本应该是"name":"张三"​的部分会变成"username":"张三"​。

相关推荐
用户7783366132111 天前
SERP API JSON Schema 演进版本管理实战
json·api
赵庆明老师3 天前
Vben精讲:21-详解web-antd:tsconfig.json
前端·json·vim
红叶舞4 天前
成数据绑定对象,在应用程序中处理完数据后,将更新的数据序列化为JSON传回远端服务器,很多移动应用使用了这种模式处理服务器端的数据。 ...
运维·服务器·json
name好难取诶5 天前
解析请求体内容(如 JSON、表单数据、XML 等) 将原始数据转换为 Python 数据结构 使转换后的数据可在 request. ...
xml·python·json
gcw10245 天前
JSONMe 简觅JSON 工具
json·json格式化·json可视化·json美化·json校验·好用的json工具·json编辑
北北牌屈四巴格!5 天前
whistle自定义修改接口返回值内容
前端·json
SQDN6 天前
Chatbox 1.22.1 获取不到模型?先验 /models,再对齐精确 model ID
人工智能·测试工具·机器学习·chatgpt·json
SunnyDays10116 天前
Python 将 Excel(XLS/XLSX)转换为 JSON:导出工作簿、工作表、单元格区域与自定义 JSON 结构
python·json·excel·excel 转 json·导出 excel 到 json·xlsx 转 json·xls 转 json
刘小八6 天前
Spring AI 结构化输出:稳定生成可校验的业务 JSON
人工智能·spring·json
CodexDave7 天前
Python 自动化接单实战(一):把 CSV 需求做成配置驱动解析器
java·python·自动化·json·数据清洗·python自动化·csv处理