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());


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM