jackson-mapper使用工具类

Posted Tom_Plus

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jackson-mapper使用工具类相关的知识,希望对你有一定的参考价值。

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

以上是关于jackson-mapper使用工具类的主要内容,如果未能解决你的问题,请参考以下文章

java 啥叫工具类

Java项目常见工具类总结

HttpClientUntils工具类的使用及注意事项(包括我改进的工具类和Controller端的注意事项附 Json 工具类)

JavaSE - 集合类-工具类

同步工具类—CountDownLatch详解

Android工具类篇 图片工具类