I have constructed a Java Object using lombok with builder pattern. But, I am getting the following exception when trying to deserialize a Java object using Jackson. This occurs for fields which has @JsonProperty
annotation.
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"])
Code Used :
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 {
}
}
Kindly help me solve this issue.
Thanks.
@JsonIgnoreProperties(ignoreUnknown = true)
– Eunuchize