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.
The @JsonPOJOBuilder annotation is used to configure a builder class to customize deserialization of a JSON document to recover POJOs when the naming convention is different from the default.
@JsonProperty can change the visibility of logical property using its access element during serialization and deserialization of JSON. @JsonAlias defines one or more alternative names for a property to be accepted during deserialization.
The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.
ConstructorProperties annotations. Lombok will automatically add this annotation to the constructors it generates. This project is compatible with Jackson 2.4 - 2.6.
You get this error because Jackson doesn't know how to map user_name
to any of your UserBuilder
fields.
You need @JsonProperty("user_name")
on the userName
field of UserBuilder
too, like that:
@JsonPOJOBuilder(withPrefix = "")
public static class UserBuilder {
@JsonProperty("user_name")
@NonNull
private String userName;
}
Your mapper need to have a means of creating User class.
You could use constructor:
@NoArgsConstructor
@AllArgsConstructor
@Getter
@ToString
@Builder
class User {
@JsonProperty("user_name")
@NonNull
private String userName;
private int userId;
}
... or point it to builder as per Tomasz Linkowski's answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With