Using the lower version of the Jackson 2 class-level @jsoninclude contains the policy bug

Source: Internet
Author: User

The source of this article: http://blog.csdn.net/chaijunkun/article/details/45110623, reprint please specify. Because I do not regularly collate the relevant blog posts, the corresponding content will be improved. It is therefore highly recommended to view this article in the original source.


Jackson is a very useful tool in the Java language for translating objects and JSON into one another. However, during one of my use, I found that the old version did not generate JSON in some cases according to our established serialization strategy. This article will use the example in the process to illustrate this problem and give a corresponding solution.


The first function to be implemented in the example is to convert the object to JSON (the serialization process), and if the object has a property value of NULL, the property does not participate in serialization, and the resulting JSON result does not contain the property.


If you've ever used Jackson, especially Jackson 2, you know that a feature can be implemented by setting the Serializationinclusion policy of the Objectmapper object:

Objectmapper mapper = new Objectmapper (); mapper.setserializationinclusion (Include.non_null);

Coincidentally, however, the object that will be serialized has a field that needs to use a special serialization method, first of all to look at the definition of this class:

/** * Animal Bean * @author Chaijunkun * @since April 18, 2015 *///such level annotations are temporarily not enabled, and then enable//@JsonInclude (Include.non_null) public when mentioned in the article Class Animal {/** name */private String name;/** Gender */@JsonSerialize (using = booleanserializer.class) Private Boolean sex;//g Etters and Setters}
In Jackson, for a boolean-type sex property, the serialization result is {"Sex": true} or{"Sex": false}. But I hope that when sex is true, the serialization result is 1, otherwise 0, which is {"Sex": 1} or {"Sex": 0}. This requires that you customize a Boolean serializer to resolve:

/** * Custom Boolean Serializer * @author Chaijunkun * @since April 18, 2015 */public class Booleanserializer extends Jsonserializer<boolea n> {@Overridepublic void serialize (Boolean value, Jsongenerator Jgen, Serializerprovider provider) throws IOException , jsonprocessingexception {if (Boolean.FALSE.equals (value)) {jgen.writenumber (0);} Else{jgen.writenumber (1);}}
to verify availability, the following unit tests have been written:

public class Jacksontest {private static final Logger Logger = Loggerfactory.getlogger (jacksontest.class); @Testpublic void Dotest () throws Ioexception{objectmapper mapper = new Objectmapper (); Mapper.setserializationinclusion ( Include.non_null); StringWriter SW = null; String json = null;try{animal Animal = new Animal ();//code block: 1, set name and sex property {Animal.setname ("dog"); Animal.setsex (true);} Code block: 2, set only the Name property {animal.setname ("Dog");} Code block: 3, nothing set {}SW = new StringWriter (); Jsongenerator generator = Mapper.getfactory (). CreateGenerator (SW); Generator.writeobject (animal); json = sw.tostring ( ); Generator.close ();} finally {ioutils.closequietly (sw);} Logger.info (JSON);}}
first block the code blocks 2 and 3, keep the code block 1, run the result as:

{"Name": "Dog", "Sex": 1}
the results look quite normal. Now separate enable code block 2, code block 3, the results are as follows:

{"Name": "Dog", "sex": null} {"Sex": null}

The problem arises, not before the default serialization policy is set, and the empty attribute does not participate in serialization? Why is the sex field still output null? The reason is that we used the @jsonserializer annotation for the sex field. After viewing the source discovery, the note has an include parameter in addition to the using parameter, which can not be set, but the implied default value is Inclusion.always, which means that the property always participates in serialization. So is there a way to block it out? You can do this by explicitly setting the Include parameter in the annotations to Inclusion.non_null, but it is not recommended in Jackson 2, but it is recommended to add @jsoninclude (include.non_null) to the attribute. Annotations to implement.


@JsonInclude (include.non_null) annotations are useful, but each attribute is marked on such an annotation is very tired, there is no better practice? Of course, it supports class-level annotations and does not participate in serialization as long as it is written on the class definition and all properties are null. OK, the question is, class-level annotations in the end good or bad use it? Or that unit test, just enable code block 2 to see the results of the run:

{"Name": "Dog", "sex": null}
The pit Daddy! It didn't work! The Empty sex field is still output. Look at the version of Jackson 2 I'm using :

<dependency><groupid>com.fasterxml.jackson.core</groupid><artifactid>jackson-databind </artifactId><version>2.1.0</version></dependency>
is a relatively old version, on the http://mvnrepository.com/to see a version of the update, the current version is 2.5.2, then updated the next try, sure enough problem solved, run the code block 2 after the output:

{"Name": "Dog"}

later, after repeated testing, to support the @jsoninclude annotation class-level use of the minimum version of 2.3.0-rc1, of course, if the candidate version is not considered, the minimum requirement for the official version is 2.3.0. So, hurry up and upgrade your Jackson 2 dependency!

Using the lower version of the Jackson 2 class-level @jsoninclude contains the policy bug

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.