@JsonProperty的使用(转载)
原作 https://www.cnblogs.com/winner-0715/p/6109037.html?utm_source=itdadao&utm_medium=referral
依赖可以用这个:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.3</version>
</dependency>
或者:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
所以引入这一个依赖就可以了
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty(value="name")。
import com.fasterxml.jackson.annotation.JsonProperty;
public class Student {
@JsonProperty(value = "real_name")
private String realName;
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "Student{" +
"realName='" + realName + '\'' +
'}';
}
}
测试
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.setRealName("zhangsan");
System.out.println(new ObjectMapper().writeValueAsString(student));
}
}
结果
{"real_name":"zhangsan"}
这里需要注意的是将对象转换成json字符串使用的方法是fasterxml.jackson提供的!!
如果使用fastjson呢?
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
import com.alibaba.fastjson.JSON;
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.setRealName("zhangsan");
System.out.println(JSON.toJSONString(student));
}
}
结果
{"realName":"zhangsan"}
可以看到,@JsonProperty(value = "real_name")没有生效,为啥?
因为fastjson不认识@JsonProperty注解呀!所以要使用jackson自己的序列化工具方法!
--------------------------
@JsonProperty不仅仅是在序列化的时候有用,反序列化的时候也有用,比如有些接口返回的是json字符串,命名又不是标准的驼峰形式,在映射成对象的时候,将类的属性上加上@JsonProperty注解,里面写上返回的json串对应的名字
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String jsonStr = "{\"real_name\":\"zhangsan\"}";
Student student = new ObjectMapper().readValue(jsonStr.getBytes(), Student.class);
System.out.println(student);
}
}
结果:
Student{realName='zhangsan'}
分类: JSON


浙公网安备 33010602011771号