0%

gson自定义类型适配器

说明

gson 实现 yyyyMMddHHmmss 格式的时间与 LocalDateTime 类型相互转换.

// 自定义序列化
JsonSerializer<LocalDateTime> serializer =
                (localDateTime, type, jsonSerializationContext) -> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
// 自定义反序列化
JsonDeserializer<LocalDateTime> deserializer =
        (jsonElement, type, jsonDeserializationContext) -> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
Gson gson = new GsonBuilder()
        .registerTypeAdapter(LocalDateTime.class, serializer)
        .registerTypeAdapter(LocalDateTime.class, deserializer).create();

// 测试 object to json
TestObject object = new TestObject();
object.setDate(LocalDateTime.now());
System.out.println(gson.toJson(object)); // {"date":"20221115141202"}
// 测试 json to object
String json = "{\"date\":\"20221115140534\"}";
System.out.println(gson.fromJson(json, TestObject.class)); // TestObject(date=2022-11-15T14:05:34)
  • TestObject.java
@Data
@ToString
public class TestObject {
    private LocalDateTime date;
}