6

I'm creating a rest service with spring and want to offer a json response:

@RequestMapping(value = "/test",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MyResponse content() {
    return rsp;
}

MyResponse may contain null values which should not be returned in the JSON response (these params should just be removed).

@XmlRootElement
class MyResponse {
}

Is that possible?

3
  • Which JSON mapper do you use? Commented Jul 17, 2015 at 13:05
  • I don't know. I'm just using spring-boot and the @RestController annotation. Commented Jul 17, 2015 at 13:06
  • 1
    Jackson is the default spring json mapper. Commented Jul 17, 2015 at 13:10

2 Answers 2

18

Try this :

@JsonInclude(JsonInclude.Include.NON_NULL)
class MyResponse {
...
}

You'll need to update your dependencies and import this :

import com.fasterxml.jackson.annotation.JsonInclude;
Sign up to request clarification or add additional context in comments.

Comments

7

Globally remove null property.

spring.jackson.default-property-inclusion = non_null

3 Comments

That's a very neat trick that is indeed elegant and handy given I almost always annotate all my DTOs with @JsonInclude(JsonInclude.Include.NON_NULL). Thanks !
I am not sure why this was not marked as an answer. Simple and straight forward yet it works.
This is really elegant. But I think it works with the latest spring-boot version 2.5.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.