@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串对应的名字

相关推荐
清水白石0084 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
yaoxin5211234 小时前
390. Java IO API - WatchDir 示例
java·前端·python
Halo_tjn6 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色6 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手6 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift
万法若空6 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商7 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫7 小时前
C++之string(OJ练习)
开发语言·c++·stl
freshman_y7 小时前
一篇介绍C语言中二级指针和二维数组的文章
c语言·开发语言
-Marks-7 小时前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本