封装jackson框架,主要有把对象转为json字符串,把json字符串转为对象,把json字符串转为对象集合,把json字符串转为泛型对象(主要用于json转为map,list等),把json字符串转为未知类型对象(主要用于json转为某个方法的返回值类型)。
public class JsonUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(MapperFeature.PROPAGATE_TRANSIENT_MARKER)
.setSerializationInclusion(JsonInclude.Include.ALWAYS);
}
/**
* 把对象转为json字符串
* @param value 被转化的对象
* @return 转化的json字符串
*/
public static String toJson(Object value) {
String result = null;
try {
result = MAPPER.writeValueAsString(value);
} catch (Exception e) {
LOGGER.error("JsonUtil.toJson error" + value, e);
}
return result;
}
/**
* 把json字符串转为对象
* @param content 被转化的json字符串
* @param valueType 转化的对象class类型
* @param <T> 泛型
* @return 转化的对象
*/
public static <T> T fromJson(String content, Class<T> valueType) {
T result = null;
try {
result = MAPPER.readValue(content, valueType);
} catch (Exception e) {
LOGGER.error("JsonUtil.fromJson error" + content, e);
}
return result;
}
/**
* 把json字符串转为对象集合
* @param content 被转化的json字符串
* @param valueType 转化的对象class类型
* @param <T> 泛型
* @return 转化的对象集合
*/
public static <T> T fromJsonToList(String content, Class<T> valueType) {
T result = null;
try {
result = MAPPER.readValue(content, MAPPER.getTypeFactory().constructParametricType(List.class, valueType));
} catch (Exception e) {
LOGGER.error("JsonUtil.fromJsonToList error" + content, e);
}
return result;
}
/**
* 把json字符串转为泛型对象
* @param content 被转化的json字符串
* @param valueTypeRef 转化的对象class类型引用
* @param <T> 泛型
* @return 转化的对象集合
*
* 可以直接转为Map或者List等泛型复杂形式
*<pre>
* TypeReference ref = new TypeReference<List<Integer>>() { };
* JsonUtil.fromJsonToTypeReference(content, ref)
*</pre>
*/
public static <T> T fromJsonToTypeReference(String content, TypeReference<T> valueTypeRef) {
T result = null;
try {
result = MAPPER.readValue(content, valueTypeRef);
} catch (Exception e) {
LOGGER.error("JsonUtil.fromJsonToTypeReference error " + content, e);
}
return result;
}
/**
* 把json字符串转为未知类型对象
* @param content 被转化的json字符串
* @param type 转化的对象type类型引用,该值可以从method.getGenericReturnType()得到
* @param <T> 泛型
* @return 转化的对象
*
* 可以直接转为Map或者List等泛型复杂形式
*<pre>
* JsonUtil.fromJsonToType(content, method.getGenericReturnType())
*</pre>
*/
public static <T> T fromJsonToType(String content, Type type) {
T result = null;
try {
result = MAPPER.readValue(content, MAPPER.getTypeFactory().constructType(type));
} catch (Exception e) {
LOGGER.error("JsonUtil.fromJsonToType error " + content, e);
}
return result;
}
}
该博客主要介绍如何封装Jackson框架,实现包括对象转json字符串、json字符串转对象、json到对象集合、json到泛型对象以及json到未知类型对象等功能。这些功能涵盖了常见的Json转换场景,如转换Map、List等,并且特别适用于将Json解析为方法返回值类型。
693

被折叠的 条评论
为什么被折叠?



