Skip to content

Commit

Permalink
api
Browse files Browse the repository at this point in the history
  • Loading branch information
oleg-cherednik committed Dec 31, 2023
1 parent 1f76ff7 commit 51ab482
Show file tree
Hide file tree
Showing 11 changed files with 393 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import ru.olegcherednik.json.jackson.datetime.serializers.JacksonZonedDateTimeSerializer;
import ru.olegcherednik.json.jackson.datetime.serializers.key.JacksonInstantKeySerializer;
import ru.olegcherednik.json.jackson.datetime.serializers.key.JacksonLocalDateKeySerializer;
import ru.olegcherednik.json.jackson.datetime.serializers.key.JacksonLocalTimeKeySerializer;

import java.time.Instant;
import java.time.LocalDate;
Expand Down Expand Up @@ -84,6 +85,7 @@ private void addKeySerializers(SetupContext context) {
SimpleSerializers ser = new SimpleSerializers();
ser.addSerializer(Instant.class, new JacksonInstantKeySerializer(instant));
ser.addSerializer(LocalDate.class, new JacksonLocalDateKeySerializer(localDate));
ser.addSerializer(LocalTime.class, new JacksonLocalTimeKeySerializer(localTime));
context.addKeySerializers(ser);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,8 @@ protected JacksonInstantSerializer withFeatures(Boolean writeZoneId, Boolean wri
return new JacksonInstantSerializer(this, _useTimestamp, writeNanoseconds, _formatter);
}

@Override
public void serialize(Instant value, JsonGenerator generator, SerializerProvider provider) throws IOException {
super.serialize(value, generator, provider);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.AccessLevel;
Expand All @@ -35,37 +36,61 @@
* @author Oleg Cherednik
* @since 01.12.2023
*/
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class JacksonLocalTimeSerializer extends LocalTimeSerializer {

private static final long serialVersionUID = 8966284219834243016L;

public static final JacksonLocalTimeSerializer INSTANCE = new JacksonLocalTimeSerializer();

public static JacksonLocalTimeSerializer with(DateTimeFormatter df) {
return new JacksonLocalTimeSerializer(INSTANCE, INSTANCE._useTimestamp, INSTANCE._useNanoseconds, df);
return new JacksonLocalTimeSerializer(INSTANCE, INSTANCE._useTimestamp, INSTANCE._useNanoseconds, df, null);
}

protected final JsonFormat.Shape shape;

protected JacksonLocalTimeSerializer() {
shape = null;
}

protected JacksonLocalTimeSerializer(JacksonLocalTimeSerializer base,
Boolean useTimestamp,
Boolean useNanoseconds,
DateTimeFormatter df) {
DateTimeFormatter df,
JsonFormat.Shape shape) {
super(base, useTimestamp, useNanoseconds, df);
this.shape = shape;
}

@Override
protected JacksonLocalTimeSerializer withFormat(Boolean useTimestamp,
DateTimeFormatter df,
JsonFormat.Shape shape) {
return new JacksonLocalTimeSerializer(this, useTimestamp, _useNanoseconds, df);
return new JacksonLocalTimeSerializer(this, useTimestamp, _useNanoseconds, df, shape);
}

@Override
public void serialize(LocalTime value, JsonGenerator generator, SerializerProvider provider)
throws IOException {
if (_formatter == null || useTimestamp(provider))
super.serialize(value, generator, provider);
public void serialize(LocalTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (useTimestamp(provider)) {
if (useNanoseconds(provider))
gen.writeNumber(value.toNanoOfDay());
else if (shape == JsonFormat.Shape.ARRAY)
super.serialize(value, gen, provider);
else
gen.writeNumber(value.toSecondOfDay());
} else if (_formatter == null)
gen.writeString(value.toString());
else
generator.writeString(_formatter.withZone(JsonSettings.SYSTEM_DEFAULT_ZONE_ID).format(value));
gen.writeString(_formatter.format(value));
}

@Override
protected boolean useNanoseconds(SerializerProvider provider) {
if (shape == JsonFormat.Shape.NUMBER_INT)
return false;
if (shape == JsonFormat.Shape.NUMBER_FLOAT)
return true;

return super.useNanoseconds(provider);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ protected boolean useContextTimeZone(SerializerProvider provider) {
}

protected boolean useTimestamp(SerializerProvider provider) {
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}

protected boolean useNanoseconds(SerializerProvider provider) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ protected String getTimestampFieldName(LocalDate value, JsonGenerator gen, Seria
}

protected boolean useTimestamp(SerializerProvider provider) {
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}

protected static boolean isEnabled(SerializerProvider provider, SerializationFeature feature) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package ru.olegcherednik.json.jackson.datetime.serializers.key;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
* @author Oleg Cherednik
* @since 31.12.2023
*/
public class JacksonLocalTimeKeySerializer extends StdSerializer<LocalTime> {

private static final long serialVersionUID = 290039851312525680L;

protected final DateTimeFormatter df;

public JacksonLocalTimeKeySerializer(DateTimeFormatter df) {
super(LocalTime.class);
this.df = df;
}

@Override
public void serialize(LocalTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String fieldName = useTimestamp(provider) ? getTimestampFieldName(value, gen, provider)
: getStringFieldName(value, gen, provider);

gen.writeFieldName(fieldName);
}

protected String getStringFieldName(LocalTime value, JsonGenerator gen, SerializerProvider provider) {
return df == null ? value.toString() : df.format(value);
}

protected String getTimestampFieldName(LocalTime value, JsonGenerator gen, SerializerProvider provider) {
if (useNanoseconds(provider))
return String.valueOf(value.toNanoOfDay());
return String.valueOf(value.toSecondOfDay());
}

protected boolean useTimestamp(SerializerProvider provider) {
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}

protected boolean useNanoseconds(SerializerProvider provider) {
return isEnabled(provider, SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
}

protected static boolean isEnabled(SerializerProvider provider, SerializationFeature feature) {
return provider.isEnabled(feature);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,12 @@ private static JsonSettings getSettings() {
.build();
}

public void shouldWriteDatesAsNumbersWhenAnnotationSettingsNumberInt() throws IOException {
DataThree data = new DataThree(ZonedDateTime.parse("2023-12-03T10:39:20.187+03:00"));
String actual = Json.writeValue(data);
String expected = ResourceData.getResourceAsString("/datetime/date_one_num.json").trim();
assertThat(actual).isEqualTo(expected);
}
// public void shouldWriteDatesAsNumbersWhenAnnotationSettingsNumberInt() throws IOException {
// DataThree data = new DataThree(ZonedDateTime.parse("2023-12-03T10:39:20.187+03:00"));
// String actual = Json.writeValue(data);
// String expected = ResourceData.getResourceAsString("/datetime/date_one_num.json").trim();
// assertThat(actual).isEqualTo(expected);
// }

public void shouldReadDatesAsNumber() throws IOException {
ZonedDateTime zdt = ZonedDateTime.parse("2023-12-03T10:39:20.187+03:00");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,22 @@

package ru.olegcherednik.json.jackson.datetime.serializers;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.testng.annotations.Test;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

Expand All @@ -35,13 +45,146 @@
@Test
public class JacksonLocalTimeSerializerTest {

public void shouldUserSuperClassLogicWhenDateFormatIsNull() throws JsonProcessingException {
SimpleModule module = new SimpleModule();
module.addSerializer(LocalTime.class, JacksonLocalTimeSerializer.INSTANCE);
public void shouldUseToStringWhenDateFormatIsNull() throws JsonProcessingException {
SimpleModule module = createModule(null);

ObjectMapper mapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localTime\":\"19:22:40.758927\"}}");
}

public void shouldUseNanoOfDayWhenWriteDateAsTimestampsNano() throws JsonProcessingException {
SimpleModule module = createModule(null);

ObjectMapper mapper = new ObjectMapper()
.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.enable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
.registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localTime\":69760758927000}}");
}

public void shouldUseSecondOfDayWhenWriteDateAsTimestamps() throws JsonProcessingException {
SimpleModule module = createModule(null);

ObjectMapper mapper = new ObjectMapper()
.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
.registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localTime\":69760}}");
}

public void shouldUseDateFormatWhenDateFormatNotNull() throws JsonProcessingException {
DateTimeFormatter df = DateTimeFormatter.ofPattern("SSS.ss:mm:HH");
SimpleModule module = createModule(df);

ObjectMapper mapper = new ObjectMapper().registerModule(module);
String json = mapper.writeValueAsString(LocalTime.parse("13:57:14.225"));
assertThat(json).isEqualTo("[13,57,14,225000000]");

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localTime\":\"758.40:22:19\"}}");
}

public void shouldSerializeTimestampWhenShapeNumberInt() throws JsonProcessingException {
@Getter
@RequiredArgsConstructor
class Data {

@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
private final LocalTime localTime;

}

DateTimeFormatter df = DateTimeFormatter.ofPattern("'[one]' HH:mm:ss.SSS");
SimpleModule module = createModule(df);

ObjectMapper mapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
.registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"localTime\":69760}");
}

public void shouldSerializeNanoWhenShapeNotNumberInt() throws JsonProcessingException {
@Getter
@RequiredArgsConstructor
class Data {

@JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT)
private final LocalTime localTime;

}

DateTimeFormatter df = DateTimeFormatter.ofPattern("'[one]' HH:mm:ss.SSS");
SimpleModule module = createModule(df);

ObjectMapper mapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
.registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"localTime\":69760758927000}");
}

public void shouldSerializeArrayWhenShapeNotNumberInt() throws JsonProcessingException {
@Getter
@RequiredArgsConstructor
class Data {

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
private final LocalTime localTime;

}

DateTimeFormatter df = DateTimeFormatter.ofPattern("'[one]' HH:mm:ss.SSS");
SimpleModule module = createModule(df);

ObjectMapper mapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
.registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalTime.parse("19:22:40.758927")));
assertThat(json).isEqualTo("{\"localTime\":[19,22,40,758]}");
}

private static SimpleModule createModule(DateTimeFormatter df) {
SimpleModule module = new SimpleModule();
module.addSerializer(LocalTime.class, JacksonLocalTimeSerializer.with(df));
return module;
}

@Getter
@EqualsAndHashCode
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
private static final class Data {

private final Map<String, LocalTime> map;

@JsonCreator
private Data(@JsonProperty("map") Map<String, LocalTime> map) {
this.map = map;
}

private Data(LocalTime value) {
this(Collections.singletonMap("localTime", value));
}

}


// public void shouldUserSuperClassLogicWhenDateFormatIsNull() throws JsonProcessingException {
// SimpleModule module = new SimpleModule();
// module.addSerializer(LocalTime.class, JacksonLocalTimeSerializer.INSTANCE);
//
// ObjectMapper mapper = new ObjectMapper().registerModule(module);
// String json = mapper.writeValueAsString(LocalTime.parse("13:57:14.225"));
// assertThat(json).isEqualTo("[13,57,14,225000000]");
// }

}
Loading

0 comments on commit 51ab482

Please sign in to comment.