Gson (由 Google 提供)是一个 Java 库,可用于将 Java 对象转换为 JSON 字符串。此外,它还可用于将 JSON 字符串转换为等效的 java 对象。
还有一些其他的 java 库也能够进行这种转换,但是 Gson 是少数不需要任何预先注释的 java 类或 java 类源代码的库之一。
Gson 还支持旧的 java 类,这些类在类型信息方面不支持泛型。它只是顺利地与这些遗留类一起工作。
在这个 gson 教程 中,我给出了一些您可以使用 Gson 执行的非常常见的任务示例。
在开始示例之前,让我们有一个 POJO 类,我们将在给定的示例中使用它。
public class Employee { private Integer id; private String firstName; private String lastName; private List<String> roles; public Employee(){ } public Employee(Integer id, String firstName, String lastName, Date birthDate){ this.id = id; this.firstName = firstName; this.lastName = lastName; } //Getters and setters @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", " + "lastName=" + lastName + ", roles=" + roles + "]"; } }
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
在 gradle 中,使用下面的依赖项。
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
可以通过两种方式创建 Gson 对象。第一种方式为您提供了一个快速的 Gson 对象,可用于更快的编码,而第二种方式使用 GsonBuilder
构建更复杂的 Gson 对象。
//1. Default constructor Gson gson = new Gson(); //2. Using GsonBuilder Gson gson = new GsonBuilder() .disableHtmlEscaping() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .serializeNulls() .create();
使用 GsonBuilder
时,还有很多其他 有用的选项 你可以提供给 Gson
对象。继续检查它们。
要将对象转换为 json,请使用 toJson()
方法。
Employee employee = new Employee(); employee.setId(1); employee.setFirstName("Lokesh"); employee.setLastName("Gupta"); employee.setRoles(Arrays.asList("ADMIN", "MANAGER")); Gson gson = new Gson(); System.out.println(gson.toJson(employee));
程序输出。
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}
要将 json 解析为对象,请使用 fromJson()
方法。
Gson gson = new Gson(); System.out.println( gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER']}", Employee.class));
程序输出。
Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER]]
在大多数情况下,即使任何类不提供默认的无参数构造函数,Gson 库也足够智能来创建实例。但是,如果您在使用具有无参数构造函数的类时发现任何问题,您可以使用 InstanceCreator
支持。使用java类类型的InstanceCreator
需要先向Gson注册。
例如,Department
没有任何默认构造函数。
public class Department { public Department(String deptName) { this.deptName = deptName; } private String deptName; public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } @Override public String toString() { return "Department [deptName="+deptName+"]"; } }
我们的 Employee
类引用了 Department
作为:
public class Employee { private Integer id; private String firstName; private String lastName; private List<String> roles; private Department department; //Department reference //Other setters and getters }
要正确使用 Department
类,我们需要为 Department
注册一个 InstanceCreator,如下所示:
class DepartmentInstanceCreator implements InstanceCreator<Department> { public Department createInstance(Type type) { return new Department("None"); } }
现在使用上面的 InstanceCreator
如下。
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator()); Gson gson = gsonBuilder.create(); System.out.println( gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta', 'roles':['ADMIN','MANAGER'],'department':{'deptName':'Finance'}}", Employee.class));
程序输出。
Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]
很多时候,我们需要写入/读取不是 java 对象默认表示的 JSON 值。在这种情况下,我们需要编写该 java 类型的自定义序列化程序和反序列化程序。
在我们的示例中,我正在为 java.util.Date
类编写序列化程序和反序列化程序,这将有助于在“dd/MM/yyyy< /strong>”格式。
import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class DateSerializer implements JsonSerializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(dateFormat.format(date)); } }
import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; public class DateDeserializer implements JsonDeserializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context) { try { return dateFormat.parse(dateStr.getAsString()); } catch (ParseException e) { e.printStackTrace(); } return null; } }
现在您可以使用 GsonBuilder
注册这些序列化器和反序列化器,如下所示:
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
序列化器和反序列化器的完整示例如下。
Employee employee = new Employee(); employee.setId(1); employee.setFirstName("Lokesh"); employee.setLastName("Gupta"); employee.setRoles(Arrays.asList("ADMIN", "MANAGER")); employee.setBirthDate(new Date()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer()); Gson gson = gsonBuilder.create(); //Convert to JSON System.out.println(gson.toJson(employee)); //Convert to java objects System.out.println(gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta', 'roles':['ADMIN','MANAGER'],'birthDate':'17/06/2014'}" , Employee.class));
程序输出。
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"],"birthDate":"17/06/2014"} Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], birthDate=Tue Jun 17 00:00:00 IST 2014]
Gson 提供的默认 JSON 输出是一种紧凑的 JSON 格式。这意味着输出的 JSON 结构中不会有任何空白。要生成更具可读性和美观的 JSON,请使用 GsonBuilder
中的 setPrettyPrinting()。
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonOutput = gson.toJson(employee);
程序输出。
{ "id": 1, "firstName": "Lokesh", "lastName": "Gupta", "roles": [ "ADMIN", "MANAGER" ], "birthDate": "17/06/2014" }
如果您正在使用的类文件已在不同版本中修改并且字段已使用 @Since 。您需要做的就是使用
GsonBuilder
的setVersion() 方法。
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer()); //Specify the version like this gsonBuilder.setVersion(1.0); Gson gson = gsonBuilder.create();
public class Employee { @Since(1.0) private Integer id; private String firstName; private String lastName; @Since(1.1) private List<String> roles; @Since(1.2) private Date birthDate; //Setters and Getters }
//Using version 1.0 fields gsonBuilder.setVersion(1.0); Output: {"id":1,"firstName":"Lokesh","lastName":"Gupta"} ///////////////////////////////////////////////////////////// //Using version 1.1 fields gsonBuilder.setVersion(1.1); Output: {"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]} ///////////////////////////////////////////////////////////// //Using version 1.2 fields gsonBuilder.setVersion(1.2); Output: {"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"],"birthDate":"17/06/2014"}
这就是这个非常有用的 java gson 库的全部内容,它可以将 java 对象从/转换为 JSON。如果您有任何疑问或反馈,请发表评论。
快乐学习!!
参考
地址:https://www.cundage.com/article/google-gson-tutorial.html