我使用带有构建器模式的lombok构建了一个Java对象.但是,当我尝试使用Jackson反序列化Java对象时,我得到以下异常.对于具有@JsonProperty注释的字段会发生这种情况.
Exception in thread “main” com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “user_name” (class User$UserBuilder), not marked as ignorable (2 known properties: “userName”, “userId”])
at [Source: (String)”{“userId”:1,”user_name”:”username”}”; line: 1, column: 26] (through reference chain: User$UserBuilder[“user_name”])
使用代码:
public class TestJson {
public static void main(String args[]) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
User user = User.builder()
.userName("username")
.userId(1)
.build();
System.out.println(user);
String string = objectMapper.writeValueAsString(user);
System.out.println(string);
user = objectMapper.readValue(string, User.class);
System.out.println(user);
}
}
@JsonDeserialize(builder = User.UserBuilder.class)
@Getter
@ToString
@Builder(toBuilder = true)
class User {
@JsonProperty("user_name")
@NonNull
private String userName;
@JsonProperty
private int userId;
@JsonPOJOBuilder(withPrefix = "")
public static class UserBuilder {
}
}
请帮我解决这个问题.
谢谢.
解决方法:
您收到此错误是因为Jackson不知道如何将user_name映射到任何UserBuilder字段.
你也需要在UserBuilder的userName字段上使用@JsonProperty(“user_name”),如下所示:
@JsonPOJOBuilder(withPrefix = "")
public static class UserBuilder {
@JsonProperty("user_name")
@NonNull
private String userName;
}