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?
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>
Use @XmlElement(nillable = true)
. At least this works for XML generation, so I believe it should work for JSON as well.
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