
com.gitee.yongzhuzl.commonutil.util.json.GsonUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commonutil Show documentation
Show all versions of commonutil Show documentation
commonutil是一个功能丰富的Java工具类库,通过封装静态方法,降低学习成本,提升工作效率。
package com.gitee.yongzhuzl.commonutil.util.json;
import com.google.gson.*;
import java.util.ArrayList;
import java.util.List;
/**
* 温馨提示:谷歌提供的一个json转换工具 --- com.google.gson.Gson
* description: JSON序列化以及反序列化工具类
* @author 朱正磊
* @date 2019-08-06 09:29:18
*/
@SuppressWarnings("ALL")
public class GsonUtil {
/**
* 温馨提示:转换之后的json字符串是进行了标准格式化输出的
* description: 将java对象进行json序列化(java对象转json字符串)
* @author 朱正磊
* @date 2019-08-05 11:11:28
* @param object 待进行序列化的java对象
* @return 返回java对象进行json序列化之后的字符串
*/
public static String toJson(Object object) {
//1、详细过程
GsonBuilder builder = new GsonBuilder();
//设置标准格式化输出
builder.setPrettyPrinting();
Gson gson = builder.create();
return gson.toJson(object);
//2、精简过程
//return new GsonBuilder().setPrettyPrinting().create().toJson(object);
}
/**
* description: 把JSON格式的数据(单个)转化为我们需要的java对象
* @author 朱正磊
* @date 2019-08-05 14:00:48
* @param json json格式字符串(单个)
* @param clazz 类对象
* @param 泛型
* @return 返回我们需要的java对象
*/
public static T fromJson(String json, Class clazz) {
//1、详细过程
Gson gson = new Gson();
return gson.fromJson(json, clazz);
//2、精简过程
//return new Gson().fromJson(json, clazz);
}
/**
* description: 把JSON格式的数据(数组)转化为我们需要的java对象集合
* @author 朱正磊
* @date 2019-08-05 14:24:54
* @param jsons json格式字符串(数组)
* @param clazz 类对象
* @param 泛型
* @return 返回我们需要的java对象集合
*/
public static List fromJsons(String jsons, Class clazz) {
List list = new ArrayList<>();
try {
Gson gson = new Gson();
JsonArray array = new JsonParser().parse(jsons).getAsJsonArray();
for (JsonElement element : array) {
list.add(gson.fromJson(element, clazz));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy