Question

Does Jackson allow you to customize how it serializes EnumMap keys? For example, if I have

public enum MyKey
{
    ABC, DEF, XYZ;

    public String getKey()
    {
        return "my-key-" + ordinal();
    }
}

and some

public class MyObject
{
    private final Map<MyKey,String> map = new EnumMap<>(MyKey.class);

    public MyObject()
    {
        map.put(MyKey.ABC, "foo");
        map.put(MyKey.DEF, "bar");
        map.put(MyKey.XYZ, "baz");
    }

    public Map<MyKey,String> getMap()
    {
        return map;
    }
}

then Jackson will serialize MyObject as

{"map":{"ABC":"foo","DEF":"bar","XYZ":"baz"}}.

Instead, I want it to serialize it like

{"map":{"my-key-0":"foo","my-key-1":"bar","my-key-2":"baz"}}. I don't want to override any toString() for this to work. Is this something even possible in Jackson at all?

I've tried doing this:

public class MyKeySerializer extends JsonSerializer<MyKey>
{
    @Override
    public void serialize(MyKey value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
    {
        jgen.writeString(value.getKey());
    }
}

then adding

public class MyObject
{
    ...

    @JsonSerialize(keyUsing = MyKeySerializer.class)
    public Map<MyKey,String> getMap()
    {
        return map;
    }

    ...
}

but that fails with a org.codehaus.jackson.JsonGenerationException: Can not write text value, expecting field name exception.

Any ideas???

Was it helpful?

Solution

Use jgen.writeFieldName(value.getKey()); instead of jgen.writeString(value.getKey()); in MyKeySerializer. As the error message indicates, Jackson expects you to write a field name (and not the text directly) while serializing keys.

I tried doing so, and I got the expected output. Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top