1

We have a HashMap with values as per below.

Map<String, Object> hm = new HashMap<String, Object>();
map.put("type:1234", "value");

The general jackson-databind api would serialize this into

<type:1234>value</type:1234>

I want it to serialize as per below.

<type_1234 value="type:1234">value</type_1234>

I tried extending StdKeySerializer and adding the custom serializer to XmlMapper as per below:

XmlMapper xMapper = new XmlMapper();
SimpleModule sm = new SimpleModule("test-module", new Version(1,0,0,null,"gId","aId"));
sm.addSerializer(new CustomKeySerializer());
xMapper.registerModule(sm);

The custom keyserializer looks as per below:

public class CustomKeySerializer extends StdKeySerializer {

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonGenerationException
    {
        if (value instanceof Date) {
            provider.defaultSerializeDateKey((Date) value, jgen);
        } else {
            jgen.writeFieldName(value.toString().replace(':', '_'));

            // TODO: Add the "value" attribute.
            final ToXmlGenerator xgen = (ToXmlGenerator) jgen;
            xgen.setNextIsAttribute(true);
            xgen.setNextName(new QName("value"));
            xgen.writeString(value.toString());
        }           
    }
} 

The "TODO" in the above code was the place where I spent lot of time and no success yet.

The next way of solving the aforementioned problem would be write a custom MapSerializer and I guess it would be little too far. Looking for your thoughts on the solutions.

Thanks.

4

1 回答 1

0

很难做到这一点,因为键序列化程序实际上只用于输出名称,对于 JSON 来说,名称是要输出的单个标记。对于 XML 输出,它可能是可行的,但在尝试之前很难知道。

所以我认为我实际上会建议编写一个完整的自定义序列化器,它可以产生精确的输出,并且不必担心键/值序列化器抽象所具有的关注点的划分。

于 2013-12-04T20:47:49.473 回答