package com.example.demo.utils;
|
|
|
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSONArray;
|
import com.alibaba.fastjson.JSONObject;
|
import com.alibaba.fastjson.serializer.SerializerFeature;
|
|
import java.util.ArrayList;
|
import java.util.Iterator;
|
import java.util.List;
|
import java.util.Map;
|
|
public class JsonUtils {
|
|
/**
|
* JSON 转 POJO
|
*/
|
public static <T> T getObject(String pojo, Class<T> tclass) {
|
try {
|
return JSONObject.parseObject(pojo, tclass);
|
} catch (Exception e) {
|
// log.error(tclass + "转 JSON 失败");
|
}
|
return null;
|
}
|
|
/**
|
* POJO 转 JSON
|
*/
|
public static <T> String getJson(T tResponse){
|
String pojo = JSONObject.toJSONString(tResponse, SerializerFeature.WriteNullStringAsEmpty);
|
return pojo;
|
}
|
|
/**
|
* List<T> 转 json 保存到数据库
|
*/
|
public static <T> String listToJson(List<T> ts) {
|
String jsons = JSON.toJSONString(ts,SerializerFeature.WriteNullStringAsEmpty);
|
return jsons;
|
}
|
|
/**
|
* json 转 List<T>
|
*/
|
public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
|
@SuppressWarnings("unchecked")
|
List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz);
|
return ts;
|
}
|
|
public static boolean isJsonStr(String jsonStr) {
|
Object object = JSON.parse(jsonStr);
|
boolean ret = true;
|
if (object instanceof JSONObject) {
|
} else if (object instanceof JSONArray) {
|
} else {
|
ret = false;
|
}
|
return ret;
|
}
|
|
public static String parseJsonStr(String jsonStr) {
|
Object object = JSON.parse(jsonStr);
|
StringBuffer retStr = new StringBuffer();
|
if (object instanceof JSONObject) {
|
JSONObject jsonObject = (JSONObject) object;
|
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
|
retStr.append('&').append(entry.getKey()).append('=').append(entry.getValue());
|
}
|
}
|
return retStr.toString();
|
}
|
|
|
|
}
|