package at.gv.egiz.eaaf.core.impl.json; import java.io.IOException; import java.io.StringWriter; import java.util.Collection; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.ser.std.StdSerializer; /** * Custom Jackson Serializer to support generic types and serialize them as * escaped Strings. * *

* Code was an example from stack-overflow. *

* * @author tlenz * */ public class EscapedJsonSerializer extends StdSerializer { private static final long serialVersionUID = 7334472154148003249L; public EscapedJsonSerializer() { super((Class) null); } @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { StringWriter str = new StringWriter(); JsonGenerator tempGen = new JsonFactory().setCodec(gen.getCodec()).createGenerator(str); if (value instanceof Collection || value.getClass().isArray()) { tempGen.writeStartArray(); if (value instanceof Collection) { for (Object it : (Collection) value) { writeTree(gen, it, tempGen); } } else if (value.getClass().isArray()) { for (Object it : (Object[]) value) { writeTree(gen, it, tempGen); } } tempGen.writeEndArray(); } else { provider.defaultSerializeValue(value, tempGen); } tempGen.flush(); gen.writeString(str.toString()); } @Override public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { StringWriter str = new StringWriter(); JsonGenerator tempGen = new JsonFactory().setCodec(gen.getCodec()).createGenerator(str); writeTree(gen, value, tempGen); tempGen.flush(); gen.writeString(str.toString()); } private void writeTree(JsonGenerator gen, Object it, JsonGenerator tempGen) throws IOException { ObjectNode tree = ((ObjectMapper) gen.getCodec()).valueToTree(it); tree.set("@class", new TextNode(it.getClass().getName())); tempGen.writeTree(tree); } }