@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();
}
}
}
