ginxo
ginxo

Reputation: 101

Hide JSON fields in Jersey RESTful

The thing is that I want to hide the null elements from a RESTFul JSON response (if it's possible). The REST controller retrieves the information from a Mongo database and because this elements doesn't exist there I would like to ignore them when they are null.

This is my REST Controller (exposed with Jersey):

@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Path(PropertiesRestURIConstants.PROPERTIES)
@Produces(MediaType.APPLICATION_JSON)
@RequestScoped
public class GetPropertiesController {

    @EJB(mappedName = PropertiesManagerRemote.MAPPED_NAME)
    PropertiesManagerRemote propertiesManager;

    @GET
    @Path(PropertiesRestURIConstants.PROPERTIES_ALL)
    public List<PropertyEntity> getAllProperties() throws DBLayerException {
        return propertiesManager.getAllProperties();
    }

    ...
    ...
    ...
}

This is my entity:

@Document(collection = "property")
public class PropertyEntity implements GenericEntity {

    @Id
    private String id;

    private String propertyName;
    private String propertyValue;

    public PropertyEntity() {
    }

    public PropertyEntity(String propertyName, String propertyValue) {
        this.propertyName = propertyName;
        this.propertyValue = propertyValue;
    }
...
...
...
}

And this is the result:

[{"id":"542c00c2ff5e0ba4ea58790d","propertyName":"property1","propertyValue":null},{"id":"542c00c2ff5e0ba4ea58790e","propertyName":"property2","propertyValue":null},{"id":"542c00c2ff5e0ba4ea58790f","propertyName":"property3","propertyValue":null}]

I use Spring Data for the persistence layer. I tried with JSONIgnore annotations and similar things, but nothing works for me. Any help will be welcome.

Thanks in advance.

Upvotes: 4

Views: 636

Answers (1)

luboskrnac
luboskrnac

Reputation: 24561

Try to annotate it this way:

@JsonInclude(Include.NON_EMPTY)
public class PropertyEntity implements GenericEntity {

Upvotes: 2

Related Questions