public class JsonUtil {
private static ObjectMapper formatedMapper;
static {
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
//defaultMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
formatedMapper = new ObjectMapper();
//序列化BigDecimal时之间输出原始数字还是科学计数, 默认false, 即是否以toPlainString()科学计数方式来输出
formatedMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
//允许将JSON空字符串强制转换为null对象值
//formatedMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
//允许单个数值当做数组处理
formatedMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
//禁止重复键, 抛出异常
formatedMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
//禁止使用int代表Enum的order()來反序列化Enum, 抛出异常
formatedMapper.enable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
//有属性不能映射的时候不报错
formatedMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//使用null表示集合类型字段是时不抛异常
formatedMapper.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
//对象为空时不抛异常
formatedMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//允许在JSON中使用c/c++风格注释
formatedMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
//强制转义非ascii字符
//formatedMapper.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
//允许未知字段
formatedMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
//在JSON中允许未引用的字段名
formatedMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
//时间格式
formatedMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
formatedMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//识别单引号
formatedMapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
//识别特殊字符
formatedMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
//识别Java8时间
//formatedMapper.registerModule(new ParameterNamesModule());
//formatedMapper.registerModule(new Jdk8Module());
//formatedMapper.registerModule(new JavaTimeModule());
//识别Guava包的类
//formatedMapper.registerModule(new GuavaModule());
// 字段保留,将null值转为""
//formatedMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
// @Override
// public void serialize(Object o, JsonGenerator jsonGenerator,
// SerializerProvider serializerProvider)
// throws IOException {
// jsonGenerator.writeString("");
// }
//});
//时间
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
formatedMapper.registerModule(javaTimeModule);
}
public static ObjectMapper ObjectMapper() {
return formatedMapper;
}
/**
* 将对象转化为json数据(时间转换格式: "yyyy-MM-dd HH:mm:ss")
*
* @param obj the obj
* @return string string
* @throws IOException the io exception
*/
public static String toJsonWithFormat(Object obj) throws IOException {
Preconditions.checkArgument(obj != null, "this argument is required; it must not be null");
return formatedMapper.writeValueAsString(obj);
}
/**
* json数据转化为对象(时间转换格式: "yyyy-MM-dd HH:mm:ss")
* User u = JacksonUtil.parseJsonWithFormat(jsonValue, User.class);
* User[] arr = JacksonUtil.parseJsonWithFormat(jsonValue, User[].class);
*
* @param <T> the type parameter
* @param jsonValue the json value
* @param valueType the value type
* @return t t
* @throws IOException the io exception
*/
public static <T> T parseJsonWithFormat(String jsonValue, Class<T> valueType) throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(jsonValue), "this argument is required; it must not be null");
return formatedMapper.readValue(jsonValue, valueType);
}
/**
* json数据转化为对象(JavaType)
*
* @param <T> the type parameter
* @param jsonValue the json value
* @param valueType the value type
* @return t t
* @throws IOException the io exception
*/
public static <T> T parseJsonWithFormat(String jsonValue, JavaType valueType) throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(jsonValue), "this argument is required; it must not be null");
return (T) formatedMapper.readValue(jsonValue, valueType);
}
/**
* json数据转化为对象(TypeReference)
*
* @param <T> the type parameter
* @param jsonValue the json value
* @param valueTypeRef the value type ref
* @return t t
* @throws IOException the io exception
*/
public static <T> T parseJsonWithFormat(String jsonValue, TypeReference<T> valueTypeRef) throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(jsonValue), "jsonValue is not null");
return (T) formatedMapper.readValue(jsonValue, valueTypeRef);
}
/**
* 转换为 json string
*
* @param obj
* @return
*/
public static String toJsonString(Object obj) {
Preconditions.checkArgument(obj != null, "this argument is required; it must not be null");
try {
return formatedMapper.writeValueAsString(obj);
} catch (Exception e) {
throw new IllegalArgumentException(String.valueOf(e.getMessage()));
}
}
/**
* 转换为对象
*
* @param obj
* @param clazz
* @param <T>
* @return
*/
public static <T> T parseObject(String obj, Class<T> clazz) {
Preconditions.checkArgument(StringUtils.isNotEmpty(obj), "this argument is required; it must not be null");
try {
return formatedMapper.readValue(obj, clazz);
} catch (Exception e) {
throw new IllegalArgumentException(String.valueOf(e.getMessage()));
}
}
/**
* 转换为对象
*
* @param obj
* @param valueTypeRef
* @param <T>
* @return
*/
public static <T> T parseObject(String obj, TypeReference<T> valueTypeRef) {
Preconditions.checkArgument(StringUtils.isNotEmpty(obj), "this argument is required; it must not be null");
try {
return formatedMapper.readValue(obj, valueTypeRef);
} catch (Exception e) {
throw new IllegalArgumentException(String.valueOf(e.getMessage()));
}
}
/**
* obj对象转换为实体类
*
* @param obj
* @param clazz
* @param <T>
* @return
*/
public static <T> T objectConvertClass(Object obj, Class<T> clazz) {
Preconditions.checkArgument(obj != null, "this argument is required; it must not be null");
try {
return formatedMapper.convertValue(obj, clazz);
} catch (Exception e) {
throw new IllegalArgumentException(String.valueOf(e.getMessage()));
}
}
/**
* obj对象转换为实体类
*
* @param obj
* @param valueTypeRef
* @param <T>
* @return
*/
public static <T> T objectConvertClass(Object obj, TypeReference<T> valueTypeRef) {
Preconditions.checkArgument(obj != null, "this argument is required; it must not be null");
try {
return formatedMapper.convertValue(obj, valueTypeRef);
} catch (Exception e) {
throw new IllegalArgumentException(String.valueOf(e.getMessage()));
}
}
}