Java Jaxb + 球衣。跳过生成的json中的空字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20079740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:57:24  来源:igfitidea点击:

Jaxb + jersey. Skipping null fields in generated json

javajsonjaxbjersey

提问by ses

I have a code:

我有一个代码:

   return Response.status(Status.BAD_REQUEST).entity(errors).build();

Where: Responseis comes from this package: javax.ws.rs.core(jersey 1.9.1);

哪里:Response来自这个包:(javax.ws.rs.core球衣1.9.1);

Where the errorsis instance of:

其中errors是实例:

@XmlRootElement
public class UserInfoValidationErrors {

    @XmlElement String username;
    @XmlElement String email;
...

Then I have JSON result like this: {"username":null,"email":"Email is not valid"}

然后我有这样的 JSON 结果: {"username":null,"email":"Email is not valid"}

If there is a way how to avoid having nullthere?

如果有办法如何避免在null那里?

回答by AlexR

Use @XmlElement(nillable = true). At least this works for XML generation, so I believe it should work for JSON as well.

使用@XmlElement(nillable = true). 至少这适用于 XML 生成,所以我相信它也适用于 JSON。

回答by Michael Doyle

If you have Jersey configured to use Hymanson to do it's JSON serialization, you can annotate your model classes with:

如果您已将 Jersey 配置为使用 Hymanson 进行 JSON 序列化,则可以使用以下命令注释模型类:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

If you want to configure Jersey to use Hymanson, you can update your web.xml as follows:

如果您想配置 Jersey 以使用 Hymanson,您可以按如下方式更新您的 web.xml:

<servlet-name>Jersey</servlet-name>
    <servlet-class>
        com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.your.package;org.codehaus.Hymanson.jaxrs</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>