Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Jersey JAX-RS, is there a way to differentiate between fields sent as null and fields not sent at all?

I'm using Jersey JAX-RS with Jackson (for serialization/deserialization) to implement a set of REST services. When a caller performs an update operation (ex. a PUT), I've generally followed the convention that null fields sent in the request are ignored when the target is updated. Only fields that were set to an actual value are updated.

However, I'd prefer it if I could differentiate between fields that were sent as null vs fields that weren't sent at all so I know to clear fields that were explicitly sent as null.

I can invent a way to accomplish this, but I'm wondering if there's anything available in the framework. It seems like a common requirement.

like image 608
MJM Avatar asked May 21 '13 22:05

MJM


1 Answers

If you are using JSON POJO support (init parameter com.sun.jersey.api.json.POJOMappingFeature to true in web.config) then a simple solution is to have "a smart setter" on your POJO:

class MyBean {
    private String foo;
    private String bar;
    private boolean fooSet;

    public String getFoo() {
        return this.foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
        this.fooSet = true;
    }

    public String getBar() {
        return this.bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

    public boolean isFooSet() {
        return this.fooSet;
    }
}

The Jackson will call the setter if the field is present (no matter the value) and will ignore it if the field is missing altogether.

For JAXB Based JSON support I don't know if the setter will ever be called so it might be necessary to write custom MessageBodyReader/MessageBodyWriters or a specialized form of JSONJAXBContext.

like image 139
Bogdan Avatar answered Oct 10 '22 06:10

Bogdan