Goal
How can I exclude all empty json objects {}
, arrays []
or arrays of empty objects [{},{}]
from the JSON response produced by Jackson in a RestController
?
Requirements and context
I'm building a Spring Boot REST API for a client. The API sends requests to a database and must produce a JSON response.
Constraints:
- The DAO layer sends native SQL queries and receives huge DB results as a List. Developers have to manually map this result to Java objects using indexes (see code below)
- SQL queries return a lot of null values (these queries can NOT be modified). Because of these null values, Java objects having only null-valued fields are frequently instantiated
Requirements:
- All fields having null value must be excluded from JSON responses. Already implemented using Jackson
@JsonInclude(JsonInclude.Include.NON_NULL)
annotation - All empty json objects
{}
or arrays[]
, or arrays of empty objects[{},{}]
must be excluded from the JSON response. This is where I'm stuck (Please see example below)
Code
Manual mapping in DAO layer:
public List<A> daoMethod() {
List<Object[]> dbResult = getDbResults();
List<A> javaObjects = new ArrayList<>();
// build nested Java objects
for (Object[] line in dbResult) {
A a = new A();
a.setProp1(line[0]);
a.setProp2(line[1]);
// and so on...
javaObjects.add(a);
return javaObjects ;
}
}
Controller method:
public ResponseEntity<A> controllerMethod() {
List<A> javaObjects = myDao.daoMethod();
return new ResponseEntity(javaObjects, HttpStatus.OK);
}
All DTO classes which must be serialized in the JSON response extend the BaseDto
class:
@JsonInclude(JsonInclude.Include.NON_NULL) // removes all fields having NULL value
public abstract class BaseDto implements Serializable{
// some properties...
}
Actual and expected results
Current JSON output:
{
prop1: "some string",
prop2: [{},{},{}],
prop3: [],
prop4: {},
}
Expected:
{
prop1: "some string"
}