gson對象序列化的示例
更新時間:2020年11月02日 14:50:16 作者:一點教程
本文介紹如何將Java對象序列化為Json文件,然后讀取該Json文件讀取回Java對象。在下面的示例中,我們創(chuàng)建了一個Student類。然后生成一個student.json文件,該文件將具有Student對象的json數(shù)據(jù)。
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對象序列化的示例的詳細內(nèi)容,更多關(guān)于Gson-對象序列化的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- kotlin gson反序列化默認值失效深入講解
- java如何利用FastJSON、Gson、Jackson三種Json格式工具自定義時間序列化
- GSON實現(xiàn)Java對象的JSON序列化與反序列化的實例教程
- Java中Gson的使用詳解
- Java實現(xiàn)操作JSON的便捷工具類完整實例【重寫Google的Gson】
- Java中利用gson解析Json實例教程
- Gson解析空字符串發(fā)生異常的處理方法
- Android利用Gson解析嵌套多層的Json的簡單方法
- GSON實現(xiàn)Java對象與JSON格式對象相互轉(zhuǎn)換的完全教程
- 舉例講解Java的JSON類庫GSON的基本用法
- Java的JSON格式轉(zhuǎn)換庫GSON的初步使用筆記
- Gson如何序列化內(nèi)部類
相關(guān)文章
Java_int、double型數(shù)組常用操作工具類(分享)
下面小編就為大家?guī)硪黄狫ava_int、double型數(shù)組常用操作工具類(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08Java中FilterInputStream和FilterOutputStream的用法詳解
這篇文章主要介紹了Java中FilterInputStream和FilterOutputStream的用法詳解,這兩個類分別用于封裝輸入和輸出流,需要的朋友可以參考下2016-06-06JSON--List集合轉(zhuǎn)換成JSON對象詳解
這篇文章主要介紹了List集合轉(zhuǎn)換成JSON對象,小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。2017-01-01Spring Boot 中application.yml與bootstrap.yml的區(qū)別
其實yml和properties文件是一樣的原理,且一個項目上要么yml或者properties,二選一的存在。這篇文章給大家介紹了Spring Boot 中application.yml與bootstrap.yml的區(qū)別,感興趣的朋友一起看看吧2018-04-04Spring MVC 中 短信驗證碼功能的實現(xiàn)方法
短信驗證功能在各個網(wǎng)站應(yīng)用都非常廣泛,那么在springmvc中如何實現(xiàn)短信驗證碼功能呢?今天小編抽時間給大家介紹下Spring MVC 中 短信驗證碼功能的實現(xiàn)方法,一起看看吧2016-09-09