Skip to content

Add @JsonKey annotation (similar to @JsonValue) for customizable serialization of Map keys #2871

@CidTori

Description

@CidTori

Describe the bug
When serializing a map key, if the key's type uses @JsonValue on one of its attributes, and if that attribute's type uses @JsonValue on one of its own attributes, the second @JsonValue is ignored, and toString() is used instead.

Version information
2.10.0

To Reproduce

    class Inner {

        @JsonValue
        String string;

        Inner(String string) {
            this.string = string;
        }

        public String toString() {
            return "Inner(String="+this.string+")";
        }

    }

    class Outer {

        @JsonValue
        Inner inner;

        Outer(Inner inner) {
            this.inner = inner;
        }

    }

    public void test() throws Exception {
        Outer outer = new Outer(new Inner("key"));
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(outer)); // outputs "key", as expected
        System.out.println(mapper.writeValueAsString(Collections.singletonMap(outer,"value"))); // outputs {"Inner(String=key)":"value"}, expected {"key":"value"}
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueIssue that seems easy to resolve and is likely a good candidate for contributors new to projecthacktoberfest-acceptedTag for issues, PRs that are explicitly marked as accepted for Hacktoberfest

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions