Gson 简明教程

Gson - Data Binding

数据绑定 API 用于使用属性访问器或注释将 JSON 转换为 POJO(纯旧 Java 对象)并从 POJO 转换回来。它有两种类型。

Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two types.

  1. Primitives Data Binding − Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans, and NULL objects.

  2. Objects Data Binding − Converts JSON to and from any JAVA type.

Gson 读写 JSON,针对两种数据绑定。数据绑定类似于用于 XML 的 JAXB 解析器。

Gson reads/writes JSON for both types of data bindings. Data Binding is analogous to JAXB parser for XML.

Primitives Data Binding

原始数据绑定是指将 JSON 映射到 JAVA 核心数据类型和内置集合。Gson 提供了各种内置适配器,可用于序列化/反序列化原始数据类型。

Primitives data binding refers to mapping of JSON to JAVA Core data types and inbuilt collections. Gson provides various inbuilt adapters which can be used to serialize/deserialize primitive data types.

Example

让我们看看原始数据绑定的实际应用。在这里,我们将直接将 JAVA 基本类型映射到 JSON,反之亦然。

Let’s see primitive data binding in action. Here we’ll map JAVA basic types directly to JSON and vice versa.

C:>Gson_WORKSPACE 中创建名为 GsonTester 的 Java 类文件。

Create a Java class file named GsonTester in C:\>Gson_WORKSPACE.

File − GsonTester.java

File − GsonTester.java

import java.util.Arrays;
import com.google.gson.Gson;

public class GsonTester {
   public static void main(String args[]) {

      Gson gson = new Gson();
      String name = "Mahesh Kumar";
      long rollNo = 1;
      boolean verified = false;
      int[] marks = {100,90,85};

      //Serialization
      System.out.println("{");
      System.out.println("name: " + gson.toJson(name) +",");
      System.out.println("rollNo: " + gson.toJson(rollNo) +",");
      System.out.println("verified: " + gson.toJson(verified) +",");
      System.out.println("marks:" + gson.toJson(marks));
      System.out.println("}");

      //De-serialization
      name = gson.fromJson("\"Mahesh Kumar\"", String.class);
      rollNo = gson.fromJson("1", Long.class);
      verified = gson.fromJson("false", Boolean.class);
      marks = gson.fromJson("[100,90,85]", int[].class);

      System.out.println("name: " + name);
      System.out.println("rollNo: " + rollNo);
      System.out.println("verified: " +verified);
      System.out.println("marks:" + Arrays.toString(marks));
   }
}

Verify the result

使用以下 javac 编译器编译类:

Compile the classes using javac compiler as follows −

C:\GSON_WORKSPACE>javac GsonTester.java

现在运行 GsonTester 以查看结果 −

Now run the GsonTester to see the result −

C:\GSON_WORKSPACE>java GsonTester

验证输出。

Verify the output.

{
   name: "Mahesh Kumar",
   rollNo: 1,
   verified: false,
   marks:[100,90,85]
}

name: Mahesh Kumar
rollNo: 1
verified: false
marks:[100, 90, 85]