The Jackson entity turns JSON to null or empty and does not participate in serialization (example explanation)

When using Jackson for serialization, we often encounter that the attribute of an entity object in the background is null. When serializing into JSON, the corresponding attribute is also null; In this way, applying the JSON object to some front-end components will report an error. (e.g. echarts)

The following summarizes two methods to solve the problem of not participating in serialization when the property is null:

Method 1:

1. The following annotation @ jsoninclude (include. Non_null) is used on the entity

Put the tag on the attribute. If the attribute is null, it will not participate in serialization; If it is placed on a class, it will work on all the properties of the class.

Specific values include:

//Include. Include. Always defaults to / / include NON_ The default attribute is the default value and does not serialize / / include NON_ The empty property is empty ('') or null and will not be serialized / / include.non_null property is null and will not be serialized

Note: if this annotation is used, the following two classes need to be introduced into the source file during import

import com. fasterxml. jackson. annotation. JsonInclude; import com. fasterxml. jackson. annotation. JsonInclude. Include;

2. The following methods are used on the code:

ObjectMapper mapper = new ObjectMapper(); mapper. setSerializationInclusion(Include.NON_NULL); User user = new User(1,"",null); String outJson = mapper. writeValueAsString(user); System. out. println(outJson);

This method is used to set the mapper object, and all serialized objects will be serialized according to the change rules.

Specific values include:

//Include. Include. Always defaults to / / include NON_ The default attribute is the default value and does not serialize / / include NON_ The empty property is empty ('') or null and will not be serialized / / include.non_null property is null and will not be serialized

Note: it only works on VO; Has no effect on map list

Method 2:

Add @ jsonserialize (include = jsonserialize. Inclusion. Non_null) annotation before the entity class

JSON was originally transformed into {"name": "name", "sex": null} after Jackson

After adding comments, the result is {"name": "name"}

The sex node has been removed

In the above article, the conversion of Jackson entity to JSON is null or empty. Not participating in serialization (example explanation) is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>