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