Gson的简单使用
程序员文章站
2024-03-16 09:36:46
...
简单介绍
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
Maven依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
对象转字符串
Gson gson = new Gson();
String jsonStr = gson.toJson(person);
字符串转对象
Gson gson = new Gson();
Person person = gson.fromJson(jsonStr, Person.class);
字符串转List
Gson gson = new Gson();
//略显复杂
List<Person> persons = gson.fromJson(jsonStr, new TypeToken<List<Person>>() {}.getType());
字符串转Map
Gson gson = new Gson();
Map<String,Object> map = gson.fromJson(jsonStr, new TypeToken<HashMap<String,Object>>() {}.getType());
注意:默认情况下在对象序列化为json字符串的时候,Gson会将字段值为null的值忽略掉。例如:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private Integer id;
private String name;
private Integer age;
public static void main(String[] args){
Person person = new Person();
person.setName("姓名");
person.setAge(18);
Gson gson = new Gson();
String jsonStr = gson.toJson(person);
System.out.println(jsonStr);
//打印结果: {"name":"姓名","age":18}
}
}
如果解决呢?构建Gson对象时使用GsonBuilder().serializeNulls().create()方法构建:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private Integer id;
private String name;
private Integer age;
public static void main(String[] args){
Person person = new Person();
person.setName("姓名");
person.setAge(18);
Gson gson = new GsonBuilder().serializeNulls().create();
String jsonStr = gson.toJson(person);
System.out.println(jsonStr);
//打印结果:{"id":null,"name":"姓名","age":18}
}
}