Jackson entity is null when transcoding to JSON does not participate in serialization rollup

Source: Internet
Author: User

First join the dependency
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

Method One, use @JsonInclude on the entity (JsonInclude.Include.NON_NULL)

1, if placed on the property , if the property is null does not participate in serialization;
2, if placed on the class , that the entire properties of the class function;

Parameter meaning:

JsonInclude.Include.ALWAYS Default

The JsonInclude.Include.NON_DEFAULT property is not serialized as the default value

JsonInclude.Include.NON_EMPTY property is empty ("") or null is not serialized

JsonInclude.Include.NON_NULL property is NULL not serialized

Before using

After use

Method Two, if you do not want to add this every time, you can configure the global definition in APPLICATION.YML, this default is effective

Spring

Jackson

Default-property-inclusion:non_null


Method Three, through the Objectmapper object to set up, the following is the test case

@Test    public  void  Test () throws jsonprocessingexception {        Resultvo resultvo = new Resultvo ();        Resultvo.setcode (0);        Resultvo.setmsg ("Success");        Objectmapper mapper = new Objectmapper ();        Mapper.setserializationinclusion (JsonInclude.Include.ALWAYS);//default        String JSON = mapper.writevalueasstring ( RESULTVO);        SYSTEM.OUT.PRINTLN (JSON);        Mapper = new Objectmapper ();        Mapper.setserializationinclusion (JsonInclude.Include.NON_NULL); The property is null not serialized        JSON = mapper.writevalueasstring (RESULTVO);        SYSTEM.OUT.PRINTLN (JSON);    }

Print as follows:

{"code": 0, "msg": " success ", "data":null} {"code": 0, "msg": " success "}




Jackson entity is null when transcoding to JSON does not participate in serialization rollup

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.