user377628
user377628

Reputation:

How can I create a custom setter for setting objects in Jersey/Jackson?

I have an entity called Checkout which has a user and an item. So when a user wants to create a new checkout object, they POST to "/checkout". Now, I was thinking to set the user and item, the user would instead include a username and a serial number, like this for example:

{
    "id": "1",
    "user": "hassan",
    "item": "sdf2ljt234jt09jsd"
}

Then I would just write custom setters in my Checkout class that take Strings rather than Users and Items:

public void setUser(String username) {
    this.user = ...
}

But Jersey is never calling my setter. Both the user and the item properties remain null, and I'm not sure why. If this isn't the proper way to set objects with Jersey/Jackson, is there something else I should be trying?

Upvotes: 1

Views: 4796

Answers (1)

Erik Gillespie
Erik Gillespie

Reputation: 3959

You can use @JsonDeserialize to specify a builder class that can hold the custom logic for going from a String to a User or Item:

@JsonDeserialize(builder = Checkout.Builder.class)
public class Checkout {
    private Long id;
    private User user;
    private Item item;

    // getters and setters

    public static class Builder {
        private Long id;
        private String username;
        private String serialNumber;

        @JsonProperty("id")
        public Builder setId(Long id) {
            this.id = id;
            return this;
        }

        @JsonProperty("user")
        public Builder setUsername(String username) {
            this.username = username;
            return this;
        }

        @JsonProperty("item")
        public Builder setSerialNumber(String serialNumber) {
            this.serialNumber = serialNumber;
            return this;
        }

        public Checkout build() {
            Checkout checkout = new Checkout();
            checkout.setId(id);
            checkout.setUser(/* lookup user by username */);
            checkout.setItem(/* lookup item by serialNumber */);
            return checkout;
        }
    }
}

Notice the use of @JsonProperty on each of the setters of the Builder class and how they use the names of the properties in your JSON. That's important to make sure your JSON structure maps properly into the builder fields.

Upvotes: 3

Related Questions