[英]Jackson EnumMap key serialization
Does Jackson allow you to customize how it serializes EnumMap keys? Jackson是否允许您自定义EnumMap键的序列化方式? 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 然后杰克逊将序列化MyObject
作为
{"map":{"ABC":"foo","DEF":"bar","XYZ":"baz"}}
. {"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"}}
. {"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. 我不想覆盖任何toString()
以使其工作。 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. 但是使用org.codehaus.jackson.JsonGenerationException: Can not write text value, expecting field name
失败org.codehaus.jackson.JsonGenerationException: Can not write text value, expecting field name
异常。
Any ideas??? 有任何想法吗???
Use jgen.writeFieldName(value.getKey());
使用jgen.writeFieldName(value.getKey());
instead of jgen.writeString(value.getKey());
而不是jgen.writeString(value.getKey());
in MyKeySerializer
. 在MyKeySerializer
。 As the error message indicates, Jackson expects you to write a field name (and not the text directly) while serializing keys. 正如错误消息所示,Jackson希望您在序列化密钥时编写字段名称(而不是直接写入文本)。
I tried doing so, and I got the expected output. 我试过这样做,我得到了预期的输出。 Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.