import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.util.ArrayList;
import java.util.List;
//gson的简单封装
final class GsonUtils {
final static Gson gson = new Gson();
public static String toJson(Object obj){
return gson.toJson(obj);
}
public static <T> T fromJsonToObject(String json,Class<?extends T> classOfT){
return gson.fromJson(json,classOfT);
}
/**
* 将JSON字符串转换为特定类型的List。
*
* @param json JSON字符串
* @param itemType 列表中项的类型
* @param <T> 列表中项的类型
* @return 转换后的List
*/
public static <T> List<T> fromJsonToList(String json, Class<T> itemType) {
List<T> resultList = new ArrayList<>();
// 将JSON字符串转换为JsonElement
JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
if (!jsonElement.isJsonArray()) {
throw new JsonParseException("JSON is not a JSON array");
}
// 将JsonElement转换为JsonArray
JsonArray jsonArray = jsonElement.getAsJsonArray();
// 遍历JsonArray,将每个元素转换为指定类型
for (JsonElement element : jsonArray) {
T item = gson.fromJson(element, itemType);
resultList.add(item);
}
return resultList;
}
}
01-09
2218

09-23
972
