package org.ssssssss.magicapi.utils;@b@@b@import com.fasterxml.jackson.core.JsonGenerator;@b@import com.fasterxml.jackson.core.JsonProcessingException;@b@import com.fasterxml.jackson.core.type.TypeReference;@b@import com.fasterxml.jackson.databind.*;@b@import com.fasterxml.jackson.databind.module.SimpleModule;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@import java.io.IOException;@b@import java.nio.charset.StandardCharsets;@b@@b@/**@b@ * JSON工具包@b@ *@b@ * @author mxd@b@ */@b@public class JsonUtils {@b@@b@ private static final ObjectMapper MAPPER = new ObjectMapper();@b@@b@ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);@b@@b@ static {@b@ MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);@b@ MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);@b@ SimpleModule simpleModule = new SimpleModule();@b@ simpleModule.addSerializer(Logger.class, new JsonSerializer<Logger>() {@b@ @Override@b@ public void serialize(Logger value, JsonGenerator gen, SerializerProvider serializers) throws IOException {@b@ gen.writeString(value.toString());@b@ }@b@ });@b@ MAPPER.registerModule(simpleModule);@b@ }@b@@b@ public static String toJsonString(Object target) {@b@ try {@b@ return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(target);@b@ } catch (JsonProcessingException e) {@b@ logger.error("json序列化失败", e);@b@ return null;@b@ }@b@ }@b@@b@ public static String toJsonStringWithoutPretty(Object target) {@b@ try {@b@ return MAPPER.writeValueAsString(target);@b@ } catch (JsonProcessingException e) {@b@ logger.error("json序列化失败", e);@b@ return null;@b@ }@b@ }@b@@b@ public static String toJsonStringWithoutLog(Object target) {@b@ try {@b@ return MAPPER.writeValueAsString(target);@b@ } catch (Exception e) {@b@ return target == null ? null : target.toString();@b@ }@b@ }@b@@b@ public static <T> T readValue(String json, TypeReference<T> typeReference) {@b@ try {@b@ return MAPPER.readValue(json, typeReference);@b@ } catch (IOException e) {@b@ logger.error("读取json失败,json:{}", json, e);@b@ return null;@b@ }@b@ }@b@@b@ public static <T> T readValue(String json, Class<T> clazz) {@b@ try {@b@ return MAPPER.readValue(json, clazz);@b@ } catch (IOException e) {@b@ logger.error("读取json失败,json:{}", json, e);@b@ return null;@b@ }@b@ }@b@@b@ public static <T> T readValue(byte[] bytes, Class<T> clazz) {@b@ try {@b@ return MAPPER.readValue(bytes, clazz);@b@ } catch (IOException e) {@b@ logger.error("读取json失败,json:{}", new String(bytes), e);@b@ return null;@b@ }@b@ }@b@@b@ public static <T> T readValue(byte[] bytes, JavaType javaType) {@b@ try {@b@ return MAPPER.readValue(bytes, javaType);@b@ } catch (IOException e) {@b@ logger.error("读取json失败,json:{}", new String(bytes), e);@b@ return null;@b@ }@b@ }@b@@b@ public static byte[] toJsonBytes(Object target) {@b@ String json = toJsonString(target);@b@ return json == null ? new byte[0] : json.getBytes(StandardCharsets.UTF_8);@b@ }@b@@b@}