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":"张三"​。

相关推荐
njsgcs3 天前
json转excel python pd
python·json·excel·pd
代码搬运媛3 天前
【架构相关】tsconfig.json 与 tsconfig.node.json、tsconfig.app.json 的关系和作用
node.js·json
aerror5 天前
json转excel xlsx文件
开发语言·python·json
掉鱼的猫5 天前
全球首个支持 IETF JSONPath (RFC 9535) 标准的 Java 框架,Snack4-Jsonpath v4.0.0 发布
java·json
吹个口哨写代码5 天前
处理文本编辑器存的json格式报错问题,对编辑器存的字段进行转换处理,再通过json返回
java·编辑器·json
APIshop6 天前
代码实例:Python 爬虫抓取与解析 JSON 数据
爬虫·python·json
得物技术6 天前
从 JSON 字符串到 Java 对象:Fastjson 1.2.83 全程解析|得物技术
java·后端·json
GISBox7 天前
GISBox如何让GeoTIFF突破Imagery Provider加载限制?
react.js·json·gis
C嘎嘎嵌入式开发7 天前
(20)100天python从入门到拿捏《JSON 数据解析》
开发语言·python·json
LazerYvTian7 天前
Json数据字段类型兼容性处理
json