使用 Jackson 的注解设置 Json 别名
在使用 Builder 模式构建对象的过程中,可能会使用一些字段名,但是在需要将该对象转换为 Json 格式时,可能需要与外部系统约定的不同字段名进行对应。这时可以使用 Jackson 提供的注解 @JsonProperty,为类中的属性设置 Json 别名。
示例代码:
public class User {
private String username;
private String password;
@JsonProperty("user_name")
public String getUsername() {
return username;
}
@JsonProperty("user_password")
public String getPassword() {
return password;
}
public static class Builder {
private User user = new User();
public Builder username(String username) {
user.username = username;
return this;
}
public Builder password(String password) {
user.password = password;
return this;
}
public User build() {
return user;
}
}
}
在上述代码中,使用了 @JsonProperty 注解为 User 类中的属性设置了 Json 别名。当使用 ObjectMapper 将该对象转换为 Json 格式时,就会使用设置的别名,而不是原本属性的名称。
示例代码:
public static void main(String[] args) throws JsonProcessingException {
User user = new User.Builder().username("admin").password("123456").build();
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
System.out.println(jsonString);
}
以上代码将输出如下结果:
{"user_name":"admin","user_password":"123456"}