I am using Java with Spring MVC and MyBatis to connect to the database. I have an account table and for some queries I need all the fields, but for others I need only some properties.
For example, to show the basic information of the account after making the query with MyBatis, some fields that I do not specify are returned as null
, false
or even 0
. Initially this was my ResponseBody:
{
"accountName": "pagos.com",
"country": "CO",
"commercialName": "pagaTu",
"city": "Chiquinquirá",
"location": null,
"secureName": null,
"description": null,
"document": "1101097231",
"localOperation": false,
"address": null,
"acceptInternationalTransactions": false,
"balance": 0
}
So I used the following annotation to avoid fields with null values:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Account implements Serializable {...}
Currently my ResponseBody removes nulls like so:
{
"accountName": "pagos.com",
"country": "CO",
"commercialName": "pagaTu",
"city": "Chiquinquirá",
"document": "1101097231",
"localOperation": false,
"acceptInternationalTransactions": false,
"balance": 0
}
But since I don't need the last 3 fields in the query either, these are returned false
and 0
. An alternative is to create a Model with just the fields I need. But first I want to know if there is another solution, maybe removing those fields while generating the ResponseBody.
The expected response is:
{
"accountName": "pagos.com",
"country": "CO",
"commercialName": "pagaTu",
"city": "Chiquinquirá",
"document": "1101097231"
}
The most comfortable thing if you are sure that those fields will never be navigated is to use @JsonIgnore on the getter that you do not want to be serialized.
As of Jackson version 2.6, you can use com.fasterxml.jackson.annotation.JsonProperty on the property you want to unserialize.
For example:
private String propertyXXX;
The javadoc documentation indicates about this type of access:
To avoid creating a DTO, you can stop using primitive data types in your entities and use wrappers instead:
In this way, the default values of these fields will no longer be
false
neither , since0
theynull
are objects. If you're worried about the memory overhead of this change, I'll tell you that it really isn't very big unless you're working with large amounts of data stored in memory (I'd imagine 100k of these items in memory at the same time, at least ).