I’m using the Jackson JSON framework to do some (de)+serialization for my web app, but as we all know… JSON isn’t typed. Here is a quick auto-typer that I created that runs when the app starts up (in tomcat). Look through the resources / references down below for more info.
First, create a basic mixin class.
package wookets.json;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeInfo.As;
import org.codehaus.jackson.annotate.JsonTypeInfo.Id;
@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property=”_type”)
public class JacksonTyping {
}
Next, create a startup (bootstrap) in your app that runs this code when the app starts in the server. I’m assuming you’re using the Spring Framework here.
def scanner = new ClassPathScanner()
scanner.addIncludeFilter(new AnnotationTypeFilter(DomainModel.class))
scanner.addIncludeFilter(new AnnotationTypeFilter(DataTransferObject.class))
for(String path : paths) {
for(Class c: scanner.getComponentClasses(path)) {
log.debug “Adding ${c.simpleName} to json mapper”
objectJsonMarshaller.getSerializationConfig().addMixInAnnotations(c, JacksonTyping.class) // outgoing
objectJsonMarshaller.getDeserializationConfig().addMixInAnnotations(c, JacksonTyping.class) // incoming
//objectJsonMarshaller.registerSubtypes(new NamedType(c, c.simpleName)) // old way
}
}
The ClassPathScanner is a nothing more than an extension of the spring class ClassPathScanningCandidateComponentProvider. It in essence will look through your java packages and return each class, which you can filter and inspect and do what have you…
Resources:
http://jackson.codehaus.org/
http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html
* this is the best reference…
http://stackoverflow.com/questions/5826928/how-can-i-prevent-jackson-from-serializing-a-polymorphic-types-annotation-prope