Gson的简单使用

Gradle

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

初使化调用

Gson gson = new Gson();

Json数组字串转字符串数据

String jsonArray = "[\"https://github.com/leavesC\",\"Java\",\"Git\",\"GitHub\"]";
String[] strings = gson.fromJson(jsonArray, String[].class);

字符串数组转Json数组字串

String jsonArray = gson.toJson(strings, String[].class);

Json数组字串转List

List<String> stringList = gson.fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());

实例:配置文件存储

//保存应用信息到本地文件
private void savePackageData() {
    try {
        FileOutputStream fout = openFileOutput("desktop_package.json", MODE_PRIVATE);
        BufferedOutputStream buffout = new BufferedOutputStream(fout);
        String jsonArray = gson.toJson(lstPackage, new TypeToken<List<Map<String, Object>>>() {
        }.getType());
        buffout.write(jsonArray.getBytes());
        buffout.close();
    } catch (Exception e) {
        log(e.getMessage());
    }
}
String jsonArray = getFileContent("desktop_package.json");
if(!jsonArray.equals("")) lstPackage = gson.fromJson(jsonArray, new TypeToken<List<Map<String, Object>>>(){}.getType());
posted @   曲幽  阅读(783)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示