欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

gson对象序列化的示例

程序员文章站 2022-08-07 23:05:48
1.编写核心类mainapp:package com.yiidian.gson;import com.google.gson.gson;import com.google.gson.gsonbuild...

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 运行测试

控制台输出:

gson对象序列化的示例

项目下生成student.json文件

gson对象序列化的示例

以上就是gson对象序列化的示例的详细内容,更多关于gson-对象序列化的资料请关注其它相关文章!