1

Im my app null values will not be serialized to json, and its ok. But in one specific case, I'd like to have null values send to client. How could I achieve that ?

class User  {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

for this class I tried with JsonInclude.Always but its defualt value that gets overriden in config later on.

filemonczyk
  • 1,613
  • 5
  • 26
  • 47
  • Possible duplicate of [How to tell Jackson to ignore a field during serialization if its value is null?](https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null) –  Feb 20 '19 at 09:26
  • @LutzHorn That question is not really a duplicate, but more the inverse of this question. – Mark Rotteveel Feb 22 '19 at 13:15

2 Answers2

2

Use JsonInclude annotation. Example:

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

public class Test {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);

        System.out.println(mapper.writeValueAsString(new User()));
    }
}

@JsonInclude
class User  {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Above code prints:

{"name":null}

Default value in JsonInclude is ALWAYS:

/**
 * Inclusion rule to use for instances (values) of types (Classes) or
 * properties annotated.
 */
public Include value() default Include.ALWAYS;

Other option is to use JsonSerialize annotation:

@JsonSerialize(include = Inclusion.ALWAYS)
class User  {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Result is the same as for JsonInclude.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • I knew and used this annotations, and it did not work, but somehow it lead me to solution. We have on classpath jackson and faster.xml the newer version, for some reason (unknown to me) the annotations from faster.xml package seems to not have any effect. it worked After replacing import from faster.xml to jackson – filemonczyk Feb 23 '19 at 07:33
  • @filemonczyk, I am glad I could help. `com.fasterxml.jackson` package comes from [`Github`](https://github.com/FasterXML) project and is long supported so definitely you should use these packages. Remove any `codehaus` or other packages from which other implementation comes. – Michał Ziober Feb 23 '19 at 09:20
0

Try

 @JsonInclude(JsonInclude.Include.ALWAYS)
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43