Google Gson 基本用法

x33g5p2x  于2021-12-25 转载在 Go  
字(2.3k)|赞(0)|评价(0)|浏览(453)

本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。

Google Gson 提供了 fromJson() 和 toJson() 两个方法用于解析和生成 JSON 字符串

fromJson() 实现了 JSON 字符串的反序列化

toJson() 实现了 JSON 字符串的序列化

示例:

1 Eclipse 中 添加 Maven 依赖

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>

2 基本数据类型的解析

@Test
public void test() {
    Gson gson = new Gson();

    boolean x = gson.fromJson("false", boolean.class);
    assertFalse(x);

    int y = gson.fromJson("77", int.class);
    assertEquals(77, y);

    double z = gson.fromJson("99.9999", double.class);
    assertEquals("[99.9999]", "[" + z + "]");

    String str = gson.fromJson("TestStr", String.class);
    assertEquals("TestStr", str);
}

3 基本数据类型的生成

@Test
public void test() {
    Gson gson = new Gson();

    String jsonBoolean = gson.toJson(true);
    assertEquals("true", jsonBoolean);

    String jsonInt = gson.toJson(77);
    assertEquals("77", jsonInt);

    String jsonDouble = gson.toJson(99.9999);
    assertEquals("99.9999", jsonDouble);

    String jsonStr = gson.toJson("TestStr");
    assertEquals("\"TestStr\"", jsonStr);
}

4 POJO 类的解析和生成

(1) POJO 类(Plain Ordinary Java Object,简单的Java对象,实际就是普通JavaBeans,是为了避免和EJB混淆所创造的简称)

public class User {

    private String account;

    private String password;

    private String name;

    private int age;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    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;
    }

    @Override
    public String toString() {
        return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + "]";
    }

}

(2) POJO 类的解析

@Test
public void test() {
    Gson gson = new Gson();

    User user = new User();
    user.setAccount("admin");
    user.setPassword("123456");
    user.setName("John");
    user.setAge(30);

    System.out.println(gson.toJson(user));
}

运行结果:

(3) POJO 类的生成

@Test
public void test() {
    Gson gson = new Gson();

    String user = "{\"account\":\"userX\",\"password\":\"0000\",\"name\":\"Kevin\",\"age\":18}";

    System.out.println(gson.fromJson(user, User.class));
}

运行结果:

相关文章