fastjson替换方案,springboot原生json
json工具类啦啦啦啦啦啦啦啦绿绿绿绿绿绿绿绿绿
·
因各种漏洞,弃用fastjson
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hello.utils.server.common.cons.CommonErrorCons;
import com.hello.utils.server.common.starter.exception.HelloException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class JsonUtils {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
/**
* 转json字符串
* @param obj:
* @return java.lang.String
*/
public static String toJsonString(Object obj) throws JsonProcessingException {
if (obj == null) {
return null;
}
return OBJECT_MAPPER.writeValueAsString(obj);
}
/**
* json转bean
* @param json:
* @param tTypeReference:
* @return T
*/
public static <T> T jsonStrToJavaBean(String json, TypeReference<T> tTypeReference) throws JsonProcessingException {
if (StringUtils.isBlank(json)) {
return null;
}
if (tTypeReference == null) {
throw new HelloException(CommonErrorCons.UNKNOWN_ERROR_MSG, null, HttpStatus.INTERNAL_SERVER_ERROR, CommonErrorCons.UNKNOWN_ERROR);
}
return OBJECT_MAPPER.readValue(json, tTypeReference);
}
/**
* 获取ObjectMapper
* @return com.fasterxml.jackson.databind.ObjectMapper
*/
public static ObjectMapper getObjectMapper(){
return OBJECT_MAPPER;
}
/**
* 构建ObjectNode
* @return com.fasterxml.jackson.databind.node.ObjectNode
*/
public static ObjectNode createObjectNode(){
return OBJECT_MAPPER.createObjectNode();
}
/**
* 对象转Map
* @param object
* @return
*/
public static Map beanToMap(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
public static <T> T jsonToBean(String json,Class<T> bean) throws JsonProcessingException {
if(StringUtils.isBlank(json)){
return null;
}
return OBJECT_MAPPER.readValue(json, bean);
};
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)