JsonUtil工具类
Posted 江湖@小小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JsonUtil工具类相关的知识,希望对你有一定的参考价值。
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapType;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: 江湖@小小白
* @Date: 2021/10/18
*/
@Slf4j
public class JsonUtil {
private JsonUtil() {
throw new IllegalStateException("JsonUtil class");
}
private static final ObjectMapper mapper = new ObjectMapper();
static {
//设置如果json多余字段忽略,就不会报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
}
/**
* json转对象
* @param json
* @param resultClazz
* @return
*/
public static <T> T jsonToObject(String json, Class<T> resultClazz) {
try {
return mapper.readValue(json, resultClazz);
} catch (IOException e) {
LOGGER.error("JSON数据:[{}]转换对象失败", json, e);
throw new RuntimeException(e);
}
}
/**
* json转List
* @param json
* @param resultClazz
* @return
*/
public static <T> List<T> jsonToList(String json, Class<T> resultClazz) {
try {
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, resultClazz);
return mapper.readValue(json, listType);
} catch (IOException e) {
LOGGER.error("JSON数据:[{}]转换对象失败", json, e);
throw new RuntimeException(e);
}
}
/**
* json转Arr
* @param json
* @param resultClazz
* @return
*/
public static <T> T[] jsonToArray(String json, Class<T> resultClazz) {
try {
ArrayType arrayType = mapper.getTypeFactory().constructArrayType(resultClazz);
return mapper.readValue(json, arrayType);
} catch (IOException e) {
LOGGER.error("JSON数据:[{}]转换对象失败", json, e);
throw new RuntimeException(e);
}
}
/**
* json转HashMap
* @param json
* @param clazz
* @return
*/
public static <T, U> Map<T, U> jsonToHashMap(String json, Class<U> clazz) {
try {
MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, clazz);
return mapper.readValue(json, mapType);
} catch (IOException e) {
LOGGER.error("JSON数据:[{}]转换对象失败", json, e);
throw new RuntimeException(e);
}
}
/**
* object转json
* @param obj
* @return
*/
public static String objectToJson(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
return mapper.writeValueAsString(obj);
} catch (IOException e) {
LOGGER.error("将[{}]转换为JSON时,出现异常", obj.getClass().getName(), e);
throw new RuntimeException(e);
}
}
}
以上是关于JsonUtil工具类的主要内容,如果未能解决你的问题,请参考以下文章