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);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
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);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
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 + "]";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
(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));
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
运行结果:
(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));
}
运行结果: