Vikas Prasad
Vikas Prasad

Reputation: 3433

Spring Boot Jackson: How to remove nulls from java array?

In my Spring Boot application when a class is written by me and I want to exclude null values from the object of that class while serialization, I just annotate the class with @JsonInclude(Include.NON_NULL) or alternatively I assign the property spring.jackson.serialization-inclusion=NON_NULL in my properties file.

But now I have a controller which returns a Java Array(not a Collection) of my class as:

@RequestMapping(path = "/reviews", method = GET, produces = APPLICATION_JSON_VALUE)
public Review[] searchReviews(@RequestParam Map<String, String> params) {

And many a times this array is not full in which case I get null for the position where there is no item.

How can I tell Jackson to omit null values present inside a Java array when serializing it?

I just gave it a shot by putting the annotation on top of my controller method like this:

@JsonInclude(JsonInclude.Include.NON_NULL)
@RequestMapping(path = "/reviews", method = GET, produces = APPLICATION_JSON_VALUE)
public Review[] searchReviews(@RequestParam Map<String, String> params) {

and this:

@RequestMapping(path = "/reviews", method = GET, produces = APPLICATION_JSON_VALUE)
public @JsonInclude(JsonInclude.Include.NON_NULL) Review[] searchReviews(@RequestParam Map<String, String> params) {

This does not give any error, but doesn't work either.

Tried with setting the property in properties file, didn't work.

Searched the github documentation for Jackson serialization features, but found nothing that enables omitting null values from Java array while serialization. The closest feature is write_empty_json_arrays, but that is not what I need.

Does the fact that java array needs to be of fixed length has to do something with this?

What shall I do to convert a java array: [object1, object2, null] of size 3 to [{}, {}] instead of [{}, {}, null]?

Upvotes: 0

Views: 1378

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30829

You should definitely change the business logic not to return an array with null values. Alternatively, you can filter out null vaues from the resultant array with Java 8's stream, e.g.:

Review[] reviews = //result;
return Arrays.stream(reviews)
   .filter(r -> r != null)
   .toArray(Review[]::new);

Upvotes: 1

Related Questions