@JsonField和@JsonProperty的使用和区别
作者:互联网
@JsonField
JsonField是位于fastjson包下的,实体类序列化为json字符串的时候,此类的原字段,序列化为json中的规定的字段
配合JSON.toJSONString(object),能将实体类转换成json字符串,配合JSON.parseObject(str,Object.class),能将字符串转换成实体类
添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
实体类
- 若属性是私有的,必须要有set*方法,否则无法反序列化
public class Person{
@JsonField(name = "name")
private String finalName;
public String getFinalName() {
return FinalName;
}
public void setFinalName(String finalName) {
FinalName = finalName;
}
}
测试类
- 注意,字符串转换为实体类时需要写原字段名
public class Test{
public static void main(String[] args){
Person person = new Person();
person.setFinalName("张三");
System.out.println(JSON.toJSONString(person));
String str = "{\"name\":\"张三\"}";
String str2 = "{\"finalName\":\"张三\"}";
System.out.println(JSON.parseObject(str,Person.class));
System.out.println(JSON.parseObject(str2,Person.class));
}
}
@JsonProperty
JsonProperty是位于jackson包里的,配合ObjectMapper的writeValueAsString(object)方法可以将实体类转换为字符串,配合ObjectMapper的readValue(str)可以将字符串转换为实体类
添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
实体类
public class Person{
@JsonProperty(value = "name")
private String finalName;
public String getFinalName() {
return FinalName;
}
public void setFinalName(String finalName) {
FinalName = finalName;
}
@Override
public String toString() {
return "Person{" +
"FinalName='" + FinalName + '\'' +
'}';
}
}
测试类
- 字符串转对象时,可以使用@JsonProperty规定的字段名
public class Test{
public static void main(String[] args){
Person person = new Person();
person.setFinalName("张三");
try{
System.out.println(new ObjectMapper().writeValueAsString(person));
} catch (JsonProcessingException e){
e.printStackTrace();
}
String str = "{\"name\":\"张三\"}";
try{
System.out.println(new ObjectMapper().readValue(str, Person.class).toString());
} catch (IOException e){
e.printStackTrace();
}
}
}
标签:JsonProperty,实体类,String,区别,class,finalName,Person,JsonField,public 来源: https://www.cnblogs.com/jtxw/p/15571660.html