Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jaxb + jersey. Skipping null fields in generated json

I have a code:

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

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

Where the errors is instance of:

@XmlRootElement
public class UserInfoValidationErrors {

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

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

If there is a way how to avoid having null there?

like image 289
ses Avatar asked Dec 25 '22 17:12

ses


2 Answers

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

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

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

<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.jackson.jaxrs</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
like image 155
Michael Doyle Avatar answered Dec 28 '22 07:12

Michael Doyle


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

like image 42
AlexR Avatar answered Dec 28 '22 06:12

AlexR