Java
GSON
serialize
deserialize

GSONでLocalDateTime型をserialize,deserializeする方法

GSONを使用して、LocalDateTime型をserialize,deserializeする場面にあったので、使用方法をメモします。

対象クラス

SampleDtoのなかにLocalDateTime型のメンバーがあります。

SampleDto.java
public class SampleDto implements JsonSerializer<SampleDto>, JsonDeserializer<SampleDto> {
    private static final long serialVersionUID = 8349420239867344581L;

    private String key;
    private LocalDateTime localDateTime = LocalDateTime.now();

    public SampleDto(String key, LocalDateTime localDateTime) {
        this.key = key;
        this.localDateTime = localDateTime;
    }

    @Override
    public JsonElement serialize(SampleDto src, Type typeOfSrc, JsonSerializationContext context) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        JsonObject result = new JsonObject();
        result.add("key", new JsonPrimitive(key));
        // LocalDateTime Serialize
        result.add("localDateTime", new JsonPrimitive(formatter.format(localDateTime)));
        return result;
    }

    @Override
    public SampleDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        final JsonObject jsonObject = json.getAsJsonObject();
        String key = jsonObject.get("key").getAsString();
        // LocalDateTime Deserialize
        LocalDateTime localDateTime = formatter.parse(jsonObject.get("localDateTime").getAsString(),
                LocalDateTime::from);

        return new SampleDto(key, localDateTime);
    }

    public LocalDateTime getLocalDateTime() {
        return localDateTime;
    }
}

テストクラス

テストクラスも以下のように作成しました。

SampleDtoTest.java
ublic class SampleDtoTest {
    private static Gson gson;
    private static final GsonBuilder gsonBuilder = new GsonBuilder();
    private static SampleDto sampleDto;

    @BeforeClass
    public static void createGson() {
        gsonBuilder.registerTypeAdapter(SampleDto.class, new SampleDto("test", LocalDateTime.of(2018, 06, 11, 00, 00)));
        gson = gsonBuilder.create();
    }

    @BeforeClass
    public static void generateData() {
        sampleDto = new SampleDto("test", LocalDateTime.of(2018, 06, 11, 00, 00));
    }

    @Test
    public void testJSON() {
        String json = gson.toJson(sampleDto);
        SampleDto fromJson = gson.fromJson(json, SampleDto.class);
        assertTrue(fromJson.getLocalDateTime().equals(sampleDto.getLocalDateTime()));
    }
}