当前位置: 移动技术网 > IT编程>开发语言>Java > gson对象序列化的示例

gson对象序列化的示例

2020年11月02日  | 移动技术网IT编程  | 我要评论
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 运行测试

控制台输出:

项目下生成student.json文件

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网