package util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.text.SimpleDateFormat;
/**
* Created by shangyl on 15/4/21.
* json处理类
*/
@SuppressWarnings({"unchecked"})
public class JacksonUtil {
private static ObjectMapper objectMapper;
static {
objectMapper = generateMapper(JsonInclude.Include.NON_EMPTY);
}
private JacksonUtil() {
}
/**
* 将json通过类型转换成对象
*/
public static <T> T fromJson(String json, Class<T> clazz)
throws IOException {
return clazz.equals(String.class) ? (T) json : objectMapper.readValue(json,
clazz);
}
/**
* 将json通过类型转换成对象
*/
public static <T> T fromJson(String json, TypeReference<?> typeReference)
throws IOException {
return (T) (typeReference.getType().equals(String.class) ? json
: objectMapper.readValue(json, typeReference));
}
/**
* 将对象转换成json
*/
public static <T> String toJson(T src) throws IOException {
return src instanceof String ? (String) src : objectMapper
.writeValueAsString(src);
}
/**
* 将对象转换成json, 可以设置输出属性
*/
public static <T> String toJson(T src, JsonInclude.Include include)
throws IOException {
if (src instanceof String) {
return (String) src;
} else {
ObjectMapper customMapper = generateMapper(include);
return customMapper.writeValueAsString(src);
}
}
/**
* 将对象转换成json, 传入配置对象
*/
public static <T> String toJson(T src, ObjectMapper mapper)
throws IOException {
if (null != mapper) {
if (src instanceof String) {
return (String) src;
} else {
return mapper.writeValueAsString(src);
}
} else {
return null;
}
}
/**
*/
public static ObjectMapper mapper() {
return objectMapper;
}
/**
* 通过Inclusion创建ObjectMapper对象
*/
private static ObjectMapper generateMapper(JsonInclude.Include include) {
ObjectMapper customMapper = new ObjectMapper();
// 设置输出时包含属性的风格
customMapper.setSerializationInclusion(include);
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
// customMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 禁止使用int代表Enum的order()來反序列化Enum,非常危險
// customMapper.configure(Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
// 所有日期格式都统一为以下样式
customMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return customMapper;
}
}
转载于:https://my.oschina.net/u/1987404/blog/611015