本篇文章為大家展示了gson實現(xiàn)對象序列化的方法,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)是一家專業(yè)提供怒江州企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計、成都做網(wǎng)站、H5建站、小程序制作等業(yè)務(wù)。10年已為怒江州眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。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+ " ]"; } }