package util;
import java.io.StringReader;
import java.io.StringWriter;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
public class JsonMapper{
ClassparameterizedClass;
public JsonMapper(Classx) {
this.parameterizedClass = x;
}
public T fromJson(String str) {
if (str == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
// make deserializer use JAXB annotations (only)
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
try {
T readValue = mapper.readValue(new StringReader(str), parameterizedClass);
return readValue;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String toJson(T jaxbObject) {
if (jaxbObject == null) {
return "null";
}
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
// make deserializer use JAXB annotations (only)
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
// make serializer use JAXB annotations (only)
SerializationConfig serializationConfig = mapper.getSerializationConfig();
serializationConfig.setAnnotationIntrospector(introspector);
serializationConfig.set(Feature.INDENT_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
try {
mapper.writeValue(stringWriter, jaxbObject);
} catch (Exception e) {
throw new RuntimeException(e);
}
String str = stringWriter.toString();
return str;
}
}
Tuesday, April 12, 2011
json jackson marshalling unmarshalling using jaxb annotations with indenting output
Subscribe to:
Posts (Atom)