Import com.google.common.collect.Lists;
Import Org.codehaus.jackson.annotate.JsonMethod;
Import Org.codehaus.jackson.map.DeserializationConfig;
Import Org.codehaus.jackson.map.ObjectMapper;
Import Org.codehaus.jackson.map.SerializationConfig;
Import Org.codehaus.jackson.map.type.TypeFactory;
Import Org.codehaus.jackson.type.JavaType;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import java.io.IOException;
Import java.util.ArrayList;
Import java.util.List;
public class Jsonutil {
private static Logger Logger = Loggerfactory.getlogger (Jsonutil.class);
private static Objectmapper mapper = new Objectmapper ();
static {
Mapper.setvisibility (Jsonmethod.field, JsonAutoDetect.Visibility.ANY);//All properties can be accessed (from private to public)
Mapper.configure (SerializationConfig.Feature.INDENT_OUTPUT, true);//Tighten the way to serialize the output
Mapper.configure (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);//deserialization, if the property has no set method, no error.
/**
* Conversion of Object to JSON
*
* @param obj
* @return
*/
public static String Object2json (Object obj) {
try {
return mapper.writevalueasstring (obj);
} catch (IOException e) {
Logger.error ("Parse Object to String error", E);
}
return null;
}
/**
* Jsonarray converted into List
*/
public static <T> list<t> jsonstr2list (String jsonstr, class<?> clazz) {
list<t> list = Lists.newarraylist ();
try {
Specify container structure and type (this is ArrayList and Clazz)
Typefactory t = typefactory.defaultinstance ();
List = Mapper.readvalue (Jsonstr,
T.constructcollectiontype (Arraylist.class, clazz));
} catch (IOException e) {
Logger.error ("Deserialization of serialization Error", E);
}
return list;
}
public static <T> T readvalue (String o, class<t> clazz) {
try {
Return Mapper.readvalue (o, clazz);
} catch (IOException e) {
Logger.error ("deserialization error", e);
}
return null;
}
public static <T> T Readjson (String jsonstr, class<?> Collectionclass,
Class<?> elementclasses) {
Objectmapper mapper = new Objectmapper ();
Javatype Javatype =
Mapper.gettypefactory (). Constructparametrictype (Collectionclass, elementclasses);
try {
Return Mapper.readvalue (Jsonstr, Javatype);
} catch (IOException e) {
E.printstacktrace ();
}
return null;
}
public static Objectmapper Getmapper () {
return mapper;
}
}
Resources:
http://a52071453.iteye.com/blog/2175398
Jackson-mapper using tool classes