您好,登錄后才能下訂單哦!
本篇文章為大家展示了gson實現對象序列化的方法,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
1.編寫核心類
MainApp:
package com.yiidian.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.*; public class MainApp { public static void main(String args[]) { MainApp tester = new MainApp(); try { Student student = new Student(); student.setAge(10); student.setName("eric"); tester.writeJSON(student); Student student1 = tester.readJSON(); System.out.println(student1); } catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } //把Java對象存儲student.json文件 private void writeJSON(Student student) throws IOException { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); FileWriter writer = new FileWriter("student.json"); writer.write(gson.toJson(student)); writer.close(); } //從student.json文件讀取Java對象 private Student readJSON() throws FileNotFoundException { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); BufferedReader bufferedReader = new BufferedReader( new FileReader("student.json")); Student student = gson.fromJson(bufferedReader, Student.class); return student; } } class Student { private String name; private int age; public Student(){} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Student [ name: "+name+", age: "+ age+ " ]"; } }
2 運行測試
控制臺輸出:
項目下生成student.json文件
上述內容就是gson實現對象序列化的方法,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。