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.

Sudheer
  • 11
  • 1

1 Answers1

0

It will be difficult to make this work, because key serializers are really only meant to output names, which for JSON are single tokens to output. For XML output it might be doable, but it is hard to know before trying out.

So I think I would actually recommend writing a full custom serializer that can produce exact output and need not worry about division of concerns that key/value serializer abstractions have.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • StaxMan, thanx for your response. So you are asking me to for custom Serializer by extending JsonSerializer ? Are you even ruling out the possibility of extending MapSerializer ? The MapSerializer seems to be my second best option and we can construct it by MapSerializer.construct. Those method parameters do confuse me a bit. Can you give me some code snippet on "construct" method ? – Sudheer Dec 06 '13 at 11:33