1、关于jackson
jackson共有1.x和2.x两个版本系列,其中1.x已废弃不再有版本发布,2.x是活跃版本。1.x和2.x不兼容,如果代码已经使用了1.x,现在想改用2.x,必须修改使用jackson的那部分代码。
2、三个核心模块
Streaming(jackson-core):低阶API库,提供流式解析工具JsonParser,流式生成工具JsonGenerator;
Annotations(jackson-annotations):jackson注解;
Databind (jackson-databind):基于java对象的序列化、反序列化能力,需要前面两个模块的支持才能实现;
当我们用jackson做JSON操作时,常用的是Databind模块的ObjectMapper类,其底层操作是基于jackson-core实现的
3、常用API
3.1 单个对象序列化
3.1.1 对象转字符串
String jsonString = objectMapper.writeValueAsString(entry);
3.1.2 对象转文件
objectMapper.writeValue(new File("entry.json"), entry);
3.1.3 对象转字节数组
byte[] array = objectMapper.writeValueAsBytes(entry);
3.2 字符串反序列化为对象
public static <T> T parse(String value, TypeReference<T> typeReference) {
if (value == null) {
return null;
}
try {
return objectMapper.readValue(value, typeReference);
} catch (IOException e) {
logger.warn("Json转换对象错误,值为:{}", value, e);
return null;
}
}
public static <T> T parse(String value, Class<T> valueType) {
if (value == null) {
return null;
}
try {
return objectMapper.readValue(value, valueType);
} catch (IOException e) {
logger.warn("Json转换对象错误parseClass,value:{}", value, e);
return null;
}
}
public static <T> List<T> parseList(String value, Class<T> valueType) {
try {
CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, valueType);
return objectMapper.readValue(value, collectionType);
} catch (Exception e) {
logger.warn("Json转换对象错误parseList,value:{}", value, e);
}
return null;
}
3.3 对象转换
public static <T> T convert(Object source, Class<T> targetType) {
if (source == null) {
return null;
}
try {
return objectMapper.convertValue(source, targetType);
} catch (IllegalArgumentException e) {
logger.warn("对象转换异常,source:{}, targetType:{}", source, targetType, e);
return null;
}
}
public static <T> T convert(Object source, TypeReference<T> typeReference) {
if (source == null) {
return null;
}
try {
return objectMapper.convertValue(source, typeReference);
} catch (IllegalArgumentException e) {
logger.warn("对象转换异常,source:{}, targetType:{}", source, typeReference, e);
return null;
}
}
public static <T extends Collection> T convertCollection(Object source, Class<T> collectionClass,Class<?> elementClass) {
if (source == null) {
return null;
}
try {
JavaType javaType = objectMapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
return objectMapper.convertValue(source, javaType);
} catch (IllegalArgumentException e) {
logger.warn("对象转换异常,source:{}, collectionClass:{}, elementClass:{}", source, collectionClass, elementClass, e);
return null;
}
}