Leon406
2023-07-07 12:45:41 +08:00
发下写的 gson 工具类, 可以参考
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <p>description:Gson 单例</p>
* <p>author:Leon</p>
* <p>date:2019/2/25 0025</p>
* <p>e-mail: deadogone@gmail.com</p>
*/
public class GsonUtils {
private static final GsonUtils INSTANCE = new GsonUtils();
private Gson gson;
private GsonUtils() {
gson = new Gson();
}
public static GsonUtils get() {
return INSTANCE;
}
public Gson gson() {
return gson;
}
public String toJson(Object obj) {
return gson.toJson(obj);
}
public <D> D fromJson(String json, Class<D> clazz) {
return gson.fromJson(json, clazz);
}
public <D> List<D> jsonToList(String json, Class<D[]> clazz) {
D[] array = gson.fromJson(json, clazz);
return Arrays.asList(array);
}
public <D> ArrayList<D> jsonToArrayList(String json, Class<D> clazz) {
Type type = new TypeToken<ArrayList<JsonObject>>() {
}.getType();
ArrayList<JsonObject> jsonObjects = gson.fromJson(json, type);
ArrayList<D> arrayList = new ArrayList<>();
for (JsonObject jsonObject : jsonObjects) {
arrayList.add(gson.fromJson(jsonObject, clazz));
}
return arrayList;
}
}