@JsonProperty作用

jackson的maven依赖

复制代码
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。

复制代码
import com.fasterxml.jackson.annotation.JsonProperty; 
   
public class Student { 
   
    @JsonProperty("name") 
    private String trueName; 
   
    public String getTrueName() { 
        return trueName; 
    } 
   
    public void setTrueName(String trueName) { 
        this.trueName = trueName; 
    } 
}  

测试一下

复制代码
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.ObjectMapper; 
   
public class Main { 
    public static void main(String[] args) throws JsonProcessingException { 
        Student student = new Student(); 
        student.setTrueName("张三"); 
        System.out.println(new ObjectMapper().writeValueAsString(student)); 
    } 
}  

得到结果

复制代码
{"name":"张三"} 

这里需要注意的是将对象转换成json字符串使用的方法是fasterxml.jackson提供的!!

@JsonProperty不仅仅是在序列化的时候有用,反序列化的时候也有用,比如有些接口返回的是json字符串,命名又不是标准的驼峰形式,在映射成对象的时候,将类的属性上加上@JsonProperty注解,里面写上返回的json串对应的名字

相关推荐
molong9311 天前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
小咕聊编程1 天前
【含文档+PPT+源码】基于SpringBoot+Gpt个人健康管理系统
java·gpt·tomcat·毕业设计·hibernate
盼哥PyAI实验室1 天前
踏上编程征程,与 Python 共舞
开发语言·python
阿无,1 天前
Java设计模式之工厂模式
java·开发语言·设计模式
weixin_307779131 天前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
哎呀呦呵1 天前
python内置模块-re模块介绍使用
java·python·mysql
louisgeek1 天前
Java CompletableFuture
java
ะัี潪ิื1 天前
精灵图(雪碧图)的生成和使用
java·css
web安全工具库1 天前
从课堂笔记到实践:深入理解Linux C函数库的奥秘
java·数据库·算法
ss2731 天前
手写MyBatis第104弹:SqlSession从工厂构建到执行器选择的深度剖析
java·开发语言·后端·mybatis