Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove null parameters in a json rest response?

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?

like image 552
membersound Avatar asked Jul 17 '15 13:07

membersound


People also ask

How do you ignore null values in JSON response?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

How do I ignore null values in post request body in spring boot?

Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!

Should JSON include null values?

You should definitely include it if there is any need to distinguish between null and undefined since those have two different meanings in Javascript. You can think of null as meaning the property is unknown or meaningless, and undefined as meaning the property doesn't exist.


2 Answers

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;
like image 89
Christophe Schutz Avatar answered Nov 15 '22 04:11

Christophe Schutz


Globally remove null property.

spring.jackson.default-property-inclusion = non_null
like image 35
robothy Avatar answered Nov 15 '22 04:11

robothy