简体   繁体   English

当使用Jersey JAX-RS时,是否可以区分以null发送的字段和根本不发送的字段?

[英]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. 我正在使用带有Jackson的Jersey JAX-RS(用于序列化/反序列化)来实现一组REST服务。 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. 当调用者执行更新操作(例如PUT)时,通常遵循以下约定:在更新目标时,将忽略请求中发送的空字段。 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. 但是,如果我可以区分以null发送的字段与根本没有发送的字段之间的区别,那么我会更喜欢,因为我知道清除显式发送为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: 如果您使用的是JSON POJO支持(在web.config中将com.sun.jersey.api.json.POJOMappingFeature初始化为true ),那么一个简单的解决方案是在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. 如果该字段存在(无论值如何),Jackson都会调用setter,如果该字段完全丢失,Jackson将忽略它。

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 . 对于基于JAXB的JSON支持,我不知道是否会调用setter,因此可能有必要编写自定义MessageBodyReader / MessageBodyWriter或专用形式的JSONJAXBContext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM