import cn.hutool.json.JSONArray;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import cn.hutool.json.JSONObject;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Jackson的工具类(搭配Hutool工具箱)
*
* @author Yang
* @date 2020/8/26 10:27
*/
public class JsonUtils {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static void jsonConfig() {
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
/**
* Json字符串转List
* @param json
* @param T
* @param <T>
* @return
* @throws Exception
*/
public static <T> List<T> str2list(String json, Class<T> T) throws Exception {
jsonConfig();
CollectionType type = objectMapper.getTypeFactory().constructCollectionType(List.class, T);
return (List)objectMapper.readValue(json, type);
}
/**
* 对象转JSON字符串
*
* @param obj
* @param <T>
* @return
*/
public static <T> String toJsonString(T obj) {
jsonConfig();
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* JSON字符串转对象
*
* @param str
* @param clazz
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, Class<T> clazz) {
jsonConfig();
if (StringUtils.isEmpty(str) || clazz == null) {
return null;
}
try {
return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 清空JSONArray 值前后空格
*
* @param array
*/
public static JSONArray jsonTrimArray(JSONArray array) {
if (array.size() > 0) {
for (int i = 0; i < array.size(); i++) {
Object object = array.get(i);
if (object != null) {
if (object instanceof String) {
array.set(i, ((String) object).trim());
} else if (object instanceof JSONObject) {
jsonTrim((JSONObject) object);
} else if (object instanceof JSONArray) {
jsonTrimArray((JSONArray) object);
}
}
}
}
return array;
}
/**
* 去除value的空格
*
* @param jsonObject jsonObject
* @return
*/
public static JSONObject jsonTrim(JSONObject jsonObject) {
Iterator<Map.Entry<String, Object>> iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
Object value = next.getValue();
if (value != null) {
if (value instanceof String) {
//清空值前后空格
jsonObject.put(next.getKey(), ((String) value).trim());
} else if (value instanceof JSONObject) {
jsonTrim((JSONObject) value);
} else if (value instanceof JSONArray) {
jsonTrimArray((JSONArray) value);
}
}
}
return jsonObject;
}
}
JackSon工具类整理
最新推荐文章于 2023-10-22 20:37:23 发布