javajsonjacksondeserializationimmutables-library

Deserialize Json Object containing map with null values to Immutable with Jackson


I'm trying to deserialize a Json object that contains the following structure but am getting an error from Jackson during deserialization due to null values appearing in the the map containing the Json object. Is there a way to deserialize these values and put them in the map as either null or an empty string?

{
    "id": "1"
    "links: {
          "a": "someLink"
          "b": null
          ....
     }
}

I have created an immutable in the following way:

@Value.Immutable
@JsonSerialize(as = ImmutableMyClass.class)
@JsonDeserialize(as = ImmutableMyClass.class)
public interface MyClass {

    @JsonProperty("id")
    String getId();

    @JsonProperty("links")
    Map<String, String> getLinks();
}

I'm reading the object into the Java POJO like this:

List<MyClass> myClassList = objectMapper.readValue(jsonString, objectMapper.getTypeFactory.constructCollectionType(List.class, ImmutableMyClass.class))

Error:

com.fasterxml.jackson.databind.exc.ValueInstantiationException problem: null value in entry: b=null

Solution

  • Maybe try something like this (to use @Value.Immutable over interface)

    @JsonProperty("links")
    Map<String, Optional<String>> getLinks();
    
    @Value.Lazy
    Map<String, String> getLinksValues() {
        return getLinks().entrySet().collect(Map.Entry::getKey, e -> e.getValue().orElse(null)));
    }
    

    or (without @Value.Immutable)

    private final Map<String, String> links;
    
    setLinks(Map<String, String> links) {
        this.links = links;
    }
    
    Map<String, String> getLinks() {
        return links;
    }