package io.gisbi.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.StreamReadConstraints; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.ObjectUtils; import java.util.Collections; import java.util.List; public class JsonUtil { private static final ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); // 配置更大的 StreamReadConstraints 限制 objectMapper.getFactory().setStreamReadConstraints( StreamReadConstraints.builder() .maxStringLength(50000000) .build() ); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public static T parse(String json, Class classOfT) { T t = null; try { t = objectMapper.readValue(json, new TypeReference() { }); } catch (JsonProcessingException e) { LogUtil.error(e.getMessage(), e); } return t; } public static T parseObject(String json, Class classOfT) { if (json == null) return null; T t = null; try { t = objectMapper.readValue(json, classOfT); } catch (JsonProcessingException e) { LogUtil.error(e.getMessage(), e); } return t; } public static T parseObject(String json, TypeReference typeReference) { if (json == null) return null; T t = null; try { t = objectMapper.readValue(json, typeReference); } catch (JsonProcessingException e) { LogUtil.error(e.getMessage(), e); } return t; } public static List parseList(String json, TypeReference> classOfT) { if (ObjectUtils.isEmpty(json)) return Collections.emptyList(); List t = null; try { t = objectMapper.readValue(json, classOfT); } catch (JsonProcessingException e) { LogUtil.error(e.getMessage(), e); } return t; } public static Object toJSONString(Object o) { try { return objectMapper.writeValueAsString(o); } catch (JsonProcessingException e) { LogUtil.error(e.getMessage(), e); return null; } } }