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);//所有的属性都可以访问到(从private 到public)
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);//缩紧的方式进行序列化输出
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);//反序列化时,属性如果没有set方法,不报错。
/**
* 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转化成list
*/
public static <T> List<T> jsonStr2List(String jsonStr, Class<?> clazz) {
List<T> list = Lists.newArrayList();
try {
// 指定容器结构和类型(这里是ArrayList和clazz)
TypeFactory t = TypeFactory.defaultInstance();
list = mapper.readValue(jsonStr,
t.constructCollectionType(ArrayList.class, clazz));
} catch (IOException e) {
logger.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("反序列化错误", 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;
}
}
参考资料:
http://a52071453.iteye.com/blog/2175398