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.
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
/MessageBodyWriter
s or a specialized form of JSONJAXBContext
.
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