Skip to content

ObjectMapper.setSerializationInclusion() is ignored for JsonAnyGetter #2592

@akhomchenko

Description

@akhomchenko

First of all: thank you a lot for an awesome library and tremendous work.

Description

I faced an issue while working with log4j2 JSON layout which uses Jackson. log4j2 JSON layout uses JsonAnyGetter to output context map. While .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) is set on the ObjectMapper of log4j2 JSON layout, null and empty values of map are still present in output.

This issue might be reproduced with plain Jackson:

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class Main {
    private static class Sample {
        private static final Map<String, String> attributes = new HashMap<>();

        static {
            attributes.put("name", "John");
            attributes.put("empty", "");
            attributes.put("null", null);
        }

        @JsonProperty("map")
        public Map<String, String> getMap() {
            return attributes;
        }

        @JsonAnyGetter
        public Map<String, String> getUnwrappedMap() {
            return attributes;
        }
    }

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

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

On versions prior to 2.9.0 (my assumption - because of #1444) output is (I have tested on 2.5.0 and 2.8.11):

{"map":{"null":null,"name":"John","empty":""},"null":null,"name":"John","empty":""}

2.9.0+ (I have tested on both 2.9.0 and 2.10.2):

{"map":{"name":"John"},"null":null,"name":"John","empty":""}

Question

Should this be considered a bug? If it is a bug which version should fix go? Should fix have backward-compatibility flag? Will you accept PR? I can try to prepare one.

Thanks.

P.S. might be related to #2289.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions