package com.cinc.permissionservice.utils; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.List; /** * @author */ @Slf4j public class JsonUtil { public final static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); /** * json字符串转化为对象 * @param json * @return */ public static <T> T jsonStrToOject(String json,Class<T> clazz){ T obj = null; try { obj = OBJECT_MAPPER.readValue(json, clazz); } catch (IOException e) { log.error("json转换错误",e); throw new RuntimeException("请求对象转JSON失败,入参为非正常格式JSON对象"); } return obj; } /** * 对象转换为JSON * @param obj * @return */ public static String objectToJsonStr(Object obj){ String jsonStr = null; try { jsonStr = OBJECT_MAPPER.writeValueAsString(obj); } catch (IOException e) { log.error("json转换错误",e); throw new RuntimeException("请求对象转JSON失败,入参为非正常格式JSON对象"); } return jsonStr; } public static <T> List<T> jsonToList(String json,Class<T> clazz){ try { JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, clazz); return OBJECT_MAPPER.readValue(json, javaType); } catch (Exception e) { log.error("json转换错误",e); throw new RuntimeException("json转换失败"); } } }