Gson-对象数据绑定

本文介绍使用Gson进行对象数据绑定,对象数据绑定是指将JSON映射到任何类型的Java对象。

1 对象数据绑定的示例

1.1 编写核心类

MainApp:

package com.yiidian.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.*;
import java.util.Arrays;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class MainApp {

    public static void main(String args[]) {

        Gson gson = new Gson();
        Student student = new Student();
        student.setAge(10);
        student.setName("eric");

        String jsonString = gson.toJson(student);
        System.out.println(jsonString);

        Student student1 = gson.fromJson(jsonString, Student.class);
        System.out.println(student1);
    }
}

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+ " ]";
    }
}

1.2 运行测试

热门文章

优秀文章