Gson入门程序

1 下载Gson包

要使用Gson库,先下载Gson包并导入到项目中

下载gson-2.3.1

2 Gson入门程序

2.1 编写核心类

MainApp:

package com.yiidian.gson;

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

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

    public static void main(String[] args){
        String jsonString = "{\"name\":\"eric\", \"age\":18}";

        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();

        Gson gson = builder.create();
        //把JSON转换为Java对象
        Student student = gson.fromJson(jsonString, Student.class);
        System.out.println(student);

        //把Java对象转换为JSON
        jsonString = gson.toJson(student);
        System.out.println(jsonString);
    }
}

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

热门文章

优秀文章