杰克逊注释@JsonProperty上使用期间的属性或方法的序列或反串行化的JSON。它带有一个可选的' name '参数,当属性名称与JSON中的' key '名称不同时,该参数很有用。默认情况下,如果键名称与属性名称匹配,则将值映射到属性值。
在下面的示例中,我们可以使用@JsonProperty注解更改JSON中的字段名称。
示例import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonPropertyAnnotationTest {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
User user = new User("Sai", "Adithya", "9959984000", "0402358700");
String data = mapper.writeValueAsString(user);
System.out.println(data);
}
}
//用户类别
class User {
@JsonProperty("first-name")
public String firstName;
@JsonProperty("last-name")
public String lastName;
@JsonProperty("mobile-phone")
public String mobilePhone;
@JsonProperty("home_phone") public String workPhone;
public User(String firstName, String lastName, String mobilePhone, String workPhone) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.mobilePhone = mobilePhone;
this.workPhone = workPhone;
}
}
输出结果{
"first-name" : "Sai",
"last-name" : "Adithya",
"mobile-phone" : "9959984000",
"home_phone" : "0402358700"
}