简体   繁体   中英

Conditionally ignore primitive typed fields with Jackson

Short Question : Is there a way to optionally serialize a field depending on it's value in jackson? Is there a way to tell jackson, something like "if a certain integer field's value is 0, don't serialize it."

(skip the following if you get what I mean)

Long Question aka Why would I want to do such a thing : Say I have a Spring MVC model class

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Foo {
    int a0;
    int a1;
    .
    .
    .
    int a99;
    String c;

    //getters and setters
}

For a new object of Foo , all int will get initialized to 0, The String to null . So if I serialize this object, I will only get int s in result, all set to 0, thanks to @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) .

In actual operation, say I have to reply with only some of the a1...a99, say a20 to a26, set to some meaningful value (to me it's something other than 0). It would be wise to send only those fields, right?

To achieve this, I can always change my int declarations to Integer . However, I have a lot of numerical computations over ints, and pondering over the net a bit and coming across links like this and this , I kinda want to stick to primitive types. Does there exist a solution satisfying both my needs?

Consider JSON Filters . I think you will need to implement your own instance of BeanPropertyFilter though.

Okay. All I was missing was @JsonInclude(Include.NON_DEFAULT)

and a default constructor.

Also I shifted my Jackson dependencies from codehaus to fasterxml .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM