Jackson custom deserializer causes data to be wiped out if null returned

Viewed 31

I have an issue when returning a null from a custom deserializer, it looks like the rest of the json will not be deserialized after.

Unfortunately I can't provide a real code, but here is a short version with all the annotations included.

What would happen if I directly return null: "Problem" will be instantiated, but both fields within the instance will be null. I thought whether @JsonUnwrapped could collide somehow with my custom deserealizer, but even if I remove an annotation, behavior maintains.

But if I consume part of the Json that represents "WannaBeNull", everything works fine, as shown in the last implemetation of the class. Using SpringBoot 2.6.6, Jackson 2.13. Would appreciate any idea about what's going on here.

A.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class A extends B {
  private C c;

  // basic setter for C, no annotations
}

B.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class B {
  @JsonUnwrapped
  private Problem problem; // a simple class with 2 fields, one of type Integer and another is String

  // basic setter and a getter for Problem, no annotations
  ...
}

C.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class C extends D {
  // nothing important here besides couple of basic fields
}

D.java

public abstract class D {
  @JsonDeserialize(using = WannaBeNullCustomDeserializer.class)
  private WannaBeNull wannaBeNull;

  // basic setter and getter, no annotation
}

WannaBeNullCustomDeserializer.java - NOT WORKING

public class WannaBeNullCustomDeserializer extends StdDeserializer<WannaBeNull> {

    public WannaBeNullCustomDeserializer (Class<?> vc) {
        super(vc);
    }

    public WannaBeNullCustomDeserializer () {
        this(null);
    }

    @Override
    public EpOrderForVcDto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return getNullValue(ctxt);
    }

}

WannaBeNullCustomDeserializer.java - WORKING

public class WannaBeNullCustomDeserializer extends StdDeserializer<WannaBeNull> {

    public WannaBeNullCustomDeserializer (Class<?> vc) {
        super(vc);
    }

    public WannaBeNullCustomDeserializer () {
        this(null);
    }

    @Override
    public EpOrderForVcDto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        new ObjectMapper().readValue(p, WannaBeNull.class);
        return getNullValue(ctxt);
    }

}

UPDATE
It looks like when inputstream (our json) is being processed, if the json that does represent that object will not be consumed and a null will be returned from a deserializer, it would mess up with tokens/further processing of the entire json, however it does not cause any kind of exception/error.

0 Answers
Related