Press "Enter" to skip to content

一个Java Json格式化的util

@Slf4j
public class JsonUtils {

    private JsonUtils() {}

    private static final ObjectMapper MAPPER = new ObjectMapper();
    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String toJson(Object obj) {
        String jsonStr = null;
        try {
            jsonStr = MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e1) {
            log.error("Object2Json.error:obj:{}", obj, e1);
        }
        return jsonStr;
    }

    public static String toPrettyPrintJson(Object obj) {
        try {
            return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e1) {
            log.error("toPrettyPrintJson exception, obj = {}", obj, e1);
        }
        return null;
    }

    public static Map<String, Object> toMap(Object bean) {
        String json = toJson(bean);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return toT(json, new TypeReference<Map<String, Object>>() {});
    }

    public static Map<String, Object> toMap(String json) {
        return toT(json, new TypeReference<Map<String, Object>>() {});
    }

    public static <T> T toT(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, clazz);
        } catch (Exception e) {
            log.error("toT exception, json = {}", json, e);
        }
        return null;
    }

    public static <T> T toT(String json, TypeReference<T> valueTypeRef) {
        try {
            return MAPPER.readValue(json, valueTypeRef);
        } catch (Exception e) {
            log.error("toT exception, json = {}", json, e);
        }
        return null;
    }

    public static <T> T toT(Map<String, Object> map, Class<T> clazz) {
        try {
            return MAPPER.convertValue(map, clazz);
        } catch (Exception e) {
            log.error("toT exception, map = {}, clazz = {}", map, clazz, e);
        }
        return null;
    }

    public static <T> List<T> toList(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, TypeFactory
                    .defaultInstance().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            log.error("toList exception, json = {}", json, e);
        }
        return null;
    }
}
发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注