Note that there are some explanatory texts on larger screens.

plurals
  1. POJackson EnumMap key serialization
    primarykey
    data
    text
    <p>Does Jackson allow you to customize how it serializes EnumMap keys? For example, if I have</p> <pre><code>public enum MyKey { ABC, DEF, XYZ; public String getKey() { return "my-key-" + ordinal(); } } </code></pre> <p>and some</p> <pre><code>public class MyObject { private final Map&lt;MyKey,String&gt; map = new EnumMap&lt;&gt;(MyKey.class); public MyObject() { map.put(MyKey.ABC, "foo"); map.put(MyKey.DEF, "bar"); map.put(MyKey.XYZ, "baz"); } public Map&lt;MyKey,String&gt; getMap() { return map; } } </code></pre> <p>then Jackson will serialize <code>MyObject</code> as</p> <p><code>{"map":{"ABC":"foo","DEF":"bar","XYZ":"baz"}}</code>.</p> <p>Instead, I want it to serialize it like</p> <p><code>{"map":{"my-key-0":"foo","my-key-1":"bar","my-key-2":"baz"}}</code>. I don't want to override any <code>toString()</code> for this to work. Is this something even possible in Jackson at all?</p> <p>I've tried doing this:</p> <pre><code>public class MyKeySerializer extends JsonSerializer&lt;MyKey&gt; { @Override public void serialize(MyKey value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(value.getKey()); } } </code></pre> <p>then adding</p> <pre><code>public class MyObject { ... @JsonSerialize(keyUsing = MyKeySerializer.class) public Map&lt;MyKey,String&gt; getMap() { return map; } ... } </code></pre> <p>but that fails with a <code>org.codehaus.jackson.JsonGenerationException: Can not write text value, expecting field name</code> exception.</p> <p>Any ideas???</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload