GSON - 自定义序列化和反序列化示例

x33g5p2x  于2022-10-07 转载在 其他  
字(8.0k)|赞(0)|评价(0)|浏览(741)

很多时候,我们需要写/读JSON值,这些值不是java对象的默认表示。在这种情况下,Gson允许你注册你自己的自定义序列器和反序列器。这是通过定义两个部分来实现的。

  • JSON序列化器。需要为一个对象定义自定义的序列化
  • JSON反序列化器。需要为一个类型定义自定义的反序列化

在我们的例子中,我们将为LocalDate和LocalDateTime类编写自定义序列化器和反序列化器。

  1. LocalDateSerializer
  2. LocalDateTimeSerializer
  3. LocalDateDeserializer
  4. LocalDateTimeDeserializer
  • 查看使用GSON将JSON转换为Java对象
  • 查看使用GSON将Java对象转换为JSON的情况

订购POJO类--要被序列化和反序列化的对象

让我们首先定义一个要被序列化和反序列化的对象 - Order.java

class Order {
    private int id;
    private String orderName;
    private String orderDesc;
    private LocalDate orderCreatedDate;
    private LocalDateTime orderCreatedDateTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public String getOrderDesc() {
        return orderDesc;
    }

    public void setOrderDesc(String orderDesc) {
        this.orderDesc = orderDesc;
    }

    public LocalDate getOrderCreatedDate() {
        return orderCreatedDate;
    }

    public void setOrderCreatedDate(LocalDate orderCreatedDate) {
        this.orderCreatedDate = orderCreatedDate;
    }

    public LocalDateTime getOrderCreatedDateTime() {
        return orderCreatedDateTime;
    }

    public void setOrderCreatedDateTime(LocalDateTime orderCreatedDateTime) {
        this.orderCreatedDateTime = orderCreatedDateTime;
    }

    @Override
    public String toString() {
        return "Order [id=" + id + ", orderName=" + orderName + ", orderDesc=" + orderDesc + ", orderCreatedDate=" +
            orderCreatedDate + ", orderCreatedDateTime=" + orderCreatedDateTime + "]";
    }
}

1. 自定义GSON LocalDateSerializer

class LocalDateSerializer implements JsonSerializer < LocalDate > {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");

    @Override
    public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDate));
    }
}

注意,我们正在将默认的本地日期 "2018-10-26 "格式化为 "2018年10月27日"。

2. 自定义GSON本地日期时间序列化器

class LocalDateTimeSerializer implements JsonSerializer < LocalDateTime > {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss");

    @Override
    public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDateTime));
    }
}

请注意,我们正在将默认的本地日期 "2018-10-26T11:09:05 "格式化为 "27::10::2018 14::35::13"。

3. 自定义GSON本地日期解析器

class LocalDateDeserializer implements JsonDeserializer < LocalDate > {
    @Override
    public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
        return LocalDate.parse(json.getAsString(),
            DateTimeFormatter.ofPattern("d-MMM-yyyy").withLocale(Locale.ENGLISH));
    }
}

4. 自定义GSON本地日期时间解析器

class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
        return LocalDateTime.parse(json.getAsString(),
            DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss").withLocale(Locale.ENGLISH));
    }
}

注册自定义序列化器和反序列化器

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());

gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());

gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());

gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());

Gson gson = gsonBuilder.setPrettyPrinting().create();

GSON自定义序列化和反序列化实例

让我们写一个完整的例子来演示GSON自定义序列化器和反序列化器的用法。

package net.javaguides.gson;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GSONCustomSerDerExample {
    public static void main(String[] args) {
        Order order = new Order();
        order.setId(100);
        order.setOrderName("Book purchase");
        order.setOrderDesc("Java Head First");
        order.setOrderCreatedDate(LocalDate.now());
        order.setOrderCreatedDateTime(LocalDateTime.now());

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());

        gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());

        gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());

        gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());

        Gson gson = gsonBuilder.setPrettyPrinting().create();

        // Convert to JSON
        System.out.println(gson.toJson(order));

        String orderJson = "{\r\n" + "  \"id\": 100,\r\n" + "  \"orderName\": \"Book purchase\",\r\n" +
            "  \"orderDesc\": \"Java Head First\",\r\n" + "  \"orderCreatedDate\": \"26-Oct-2018\",\r\n" +
            "  \"orderCreatedDateTime\": \"26::Oct::2018 11::09::05\",\r\n" +
            "  \"orderCreatedZonedDateTime\": \"Oct 26 2018  11:09 AM\"\r\n" + "}";
        // Convert to java objects
        System.out.println(gson.fromJson(orderJson, Order.class));

    }

}

class Order {
    private int id;
    private String orderName;
    private String orderDesc;
    private LocalDate orderCreatedDate;
    private LocalDateTime orderCreatedDateTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public String getOrderDesc() {
        return orderDesc;
    }

    public void setOrderDesc(String orderDesc) {
        this.orderDesc = orderDesc;
    }

    public LocalDate getOrderCreatedDate() {
        return orderCreatedDate;
    }

    public void setOrderCreatedDate(LocalDate orderCreatedDate) {
        this.orderCreatedDate = orderCreatedDate;
    }

    public LocalDateTime getOrderCreatedDateTime() {
        return orderCreatedDateTime;
    }

    public void setOrderCreatedDateTime(LocalDateTime orderCreatedDateTime) {
        this.orderCreatedDateTime = orderCreatedDateTime;
    }

    @Override
    public String toString() {
        return "Order [id=" + id + ", orderName=" + orderName + ", orderDesc=" + orderDesc + ", orderCreatedDate=" +
            orderCreatedDate + ", orderCreatedDateTime=" + orderCreatedDateTime + "]";
    }
}

class LocalDateSerializer implements JsonSerializer < LocalDate > {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");

    @Override
    public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDate));
    }
}

class LocalDateTimeSerializer implements JsonSerializer < LocalDateTime > {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss");

    @Override
    public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDateTime));
    }
}

class LocalDateDeserializer implements JsonDeserializer < LocalDate > {
    @Override
    public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
        return LocalDate.parse(json.getAsString(),
            DateTimeFormatter.ofPattern("d-MMM-yyyy").withLocale(Locale.ENGLISH));
    }
}

class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
        return LocalDateTime.parse(json.getAsString(),
            DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss").withLocale(Locale.ENGLISH));
    }
}

输出:

{
  "id": 100,
  "orderName": "Book purchase",
  "orderDesc": "Java Head First",
  "orderCreatedDate": "27-Oct-2018",
  "orderCreatedDateTime": "27::Oct::2018 14::35::13"
}
Order [id=100, orderName=Book purchase, orderDesc=Java Head First, orderCreatedDate=2018-10-26, orderCreatedDateTime=2018-10-26T11:09:05]

相关文章