Raunak
Raunak

Reputation: 6507

Jackson with Builder Pattern

I've seen many questions around using jackson to serialize/deserialize java objects using builder patter, however, I can't figure out why this code below won't work. I'm using Jackson version 2.5.4

@JsonDeserialize(builder = User.Builder.class)
public class User {

    private String name;

    private User(Builder builder) {
        this.name=builder.name;
    }

    @JsonPOJOBuilder(buildMethodName = "build")
    public static class Builder {
        private String name;

        public Builder name(String name) {
            this.name = name;
            return this;
        }

        public User build() {
            return new Learner(this);
        }
    }
}

Trying to output the string representation always prints an empty list {}

Upvotes: 1

Views: 4589

Answers (1)

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

By default the @JsonPOJOBuilderexpects the builder methods to starts with with prefix. You should override this in the annotation: @JsonPOJOBuilder(withPrefix = "")

You should also mark the name field with the @JsonProperty annotation, or add a getter, or use the JacksonFeatureAutoDetect feature; otherwise Jackson does not see name as a JSON property.

Upvotes: 6

Related Questions