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.