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

I am using JAX-RS Jersey with Jackson (for serialization / deserialization) to implement a set of REST services. When the caller performs an update operation (for example, PUT), I usually followed the agreement that empty fields sent in the request are ignored when updating the target. Only those fields that have been set to the actual value are updated.

However, I would prefer that I can distinguish between fields that were sent as fields with zero vs that were not sent at all, so I know to clear the fields that were explicitly sent as null.

I can come up with a way to do this, but I wonder if there is anything in this area. This seems like a general requirement.

+6
source share
1 answer

If you are using JSON POJO support (init com.sun.jersey.api.json.POJOMappingFeature parameter to true in web.config ), then a simple solution is to have an “intelligent 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; } } 

Jackson will call the setter if the field is present (regardless of the value), and will ignore it if the field is completely absent.

For JAXB-based JSX support, I don't know if the calling call will ever be called, so you might need to write a custom MessageBodyReader / MessageBodyWriter or a specialized form of JSONJAXBContext .

+2
source

Source: https://habr.com/ru/post/945524/


All Articles