J'étais dans une situation où j'utilisais GSON pour sérialiser et désérialiser le type LocalDateTime, alors notez comment l'utiliser.
Il existe un membre de type LocalDateTime dans SampleDto.
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;
}
}
J'ai également créé une classe de test comme suit.
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()));
}
}