@JsonProperty的使用

jackson的maven依赖

[html]   view plain  copy
  1. <dependency>  
  2.     <groupId>com.fasterxml.jackson.core</groupId>  
  3.     <artifactId>jackson-databind</artifactId>  
  4.     <version>2.5.3</version>  
  5. </dependency>  
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。

[java]   view plain  copy
  1. import com.fasterxml.jackson.annotation.JsonProperty;  
  2.   
  3. public class Student {  
  4.   
  5.     @JsonProperty("name")  
  6.     private String trueName;  
  7.   
  8.     public String getTrueName() {  
  9.         return trueName;  
  10.     }  
  11.   
  12.     public void setTrueName(String trueName) {  
  13.         this.trueName = trueName;  
  14.     }  
  15. }  
测试一下

[java]   view plain  copy
  1. import com.fasterxml.jackson.core.JsonProcessingException;  
  2. import com.fasterxml.jackson.databind.ObjectMapper;  
  3.   
  4. public class Main {  
  5.     public static void main(String[] args) throws JsonProcessingException {  
  6.         Student student = new Student();  
  7.         student.setTrueName("张三");  
  8.         System.out.println(new ObjectMapper().writeValueAsString(student));  
  9.     }  
  10. }  
得到结果
[html]   view plain  copy
  1. {"name":"张三"}  
这里需要注意的是将对象转换成json字符串使用的方法是 fasterxml.jackson 提供的!!

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


jackson的jar包点我免费下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值