GsonUtils工具类

public class GsonUtils {

    private static final String TAG = GsonUtils.class.getSimpleName();

    // 无参的私有构造方法
    private GsonUtils() {

    }

    // 不用创建对象,直接使用 gson. 就可以调用方法
    private static Gson gson = null;

    /**
     * 默认的时间格式化
     */
    private static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 判断gson对象是否存在了,不存在则创建对象
     */
    static {
        if (gson == null) {
            // gson = new Gson();
            // 当使用 GsonBuilder 方式时属性为空的时候输出来的json字符串是有键值key的,显示形式是"key":null,而直接 new 出来的就没有"key":null的
            gson = buildGson();
        }
    }

    /**
     * 默认的 GSON 初始化
     */
    public static Gson buildGson() {
        Gson gson = new Gson().newBuilder()
                .setDateFormat(DATE_FORMAT_DEFAULT)
                .create();
        return gson;
    }

    /**
     * 将对象转成json格式
     * Bean To Json
     *
     * @param object
     * @return String
     */
    public static String beanToJson(Object object) {
        String jsonString = null;
        try {
            if (gson != null) {
                jsonString = gson.toJson(object);
            }
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Bean cast Json format exception:" + e);
        }
        return jsonString;
    }

    /**
     * 将 json 转成特定的 cls 的对象
     * Json To Bean
     *
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> T jsonToBean(String jsonString, Class<T> cls) {
        T t = null;
        try {
            if (gson != null) {
                // 传入json对象和对象类型,将json转成对象
                t = gson.fromJson(jsonString, cls);
            }
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Json cast Bean Json format exception:" + e);
        }
        return t;
    }

    /**
     * json字符串转成list
     * 解决泛型问题
     * 备注:
     * List list=gson.fromJson(jsonString, new TypeToken<List>() {}.getType());
     * 该方法会报泛型类型擦除问题
     *
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> List<T> jsonToList(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList();
        try {
            if (gson != null) {
                JsonArray array = new JsonParser().parse(jsonString).getAsJsonArray();
                for (final JsonElement elem : array) {
                    list.add(gson.fromJson(elem, cls));
                }
            }
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Json cast List Json format exception:" + e);
        }
        return list;
    }

    /**
     * json 字符串转成 list map
     * Json To List<Map<String,T>>
     *
     * @param jsonString
     * @return
     */
    public static <T> List<Map<String, T>> jsonToListMaps(String jsonString) {
        List<Map<String, T>> list = null;
        try {
            if (gson != null) {
                list = gson.fromJson(jsonString,
                        new TypeToken<List<Map<String, T>>>() {
                        }.getType());
            }
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Json cast List Json format exception:" + e);
        }
        return list;
    }

    /**
     * json 字符串转成 map 的
     * Json To Map
     *
     * @param jsonString
     * @return
     */
    public static <T> Map<String, T> JsonToMaps(String jsonString) {
        Map<String, T> map = null;
        try {
            if (gson != null) {
                map = gson.fromJson(jsonString, new TypeToken<Map<String, T>>() {
                }.getType());
            }
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Json cast Map Json format exception:" + e);
        }
        return map;
    }

    public static File saveJsonToFile(String json, String path) {
        File file = new File(path);
        if (TextUtils.isEmpty(json) || TextUtils.isEmpty(path)) {
            Log.e(TAG, "saveStrToFile param invalid");
            return file;
        }
        if (file.exists()) {
            if (!file.delete()) {
                Log.e(TAG, "file exist but delete fail");
                return file;
            }
        }
        FileChannel fc = null;
        try {
            fc = new FileOutputStream(path).getChannel();
            fc.write(ByteBuffer.wrap(json.getBytes(StandardCharsets.UTF_8)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, "saveStrToFile FileNotFoundException");
        } catch (IOException e) {
            Log.e(TAG, "saveStrToFile IOException");
        } finally {
            IoUtils.closeQuietly(fc);
        }
        return file;
    }

    public static String readJsonFromFile(String fileName) {
        StringBuffer result = new StringBuffer();
        if (TextUtils.isEmpty(fileName)) {
            return result.toString();
        }
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                new FileInputStream(fileName), StandardCharsets.UTF_8))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "readStrFromFile FileNotFoundException");
        } catch (IOException e) {
            Log.e(TAG, "readStrFromFile IOException");
        }
        return result.toString();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值