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 51ab482 commit e0633b5
Show file tree
Hide file tree
Showing 9 changed files with 231 additions and 30 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.JacksonLocalDateTimeKeySerializer;
import ru.olegcherednik.json.jackson.datetime.serializers.key.JacksonLocalTimeKeySerializer;

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import ru.olegcherednik.json.api.JsonSettings;

import java.io.IOException;
import java.time.LocalDateTime;
Expand Down Expand Up @@ -61,12 +60,13 @@ protected JacksonLocalDateTimeSerializer withFormat(Boolean useTimestamp,
}

@Override
public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider)
throws IOException {
if (_formatter == null || useTimestamp(provider))
super.serialize(value, generator, provider);
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (useTimestamp(provider))
super.serialize(value, gen, provider);
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));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@ public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider pro
gen.writeFieldName(fieldName);
}

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

protected String getTimestampFieldName(LocalDate value, JsonGenerator gen, SerializerProvider provider) {
return String.valueOf(value.toEpochDay());
}

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

protected boolean useTimestamp(SerializerProvider provider) {
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* 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.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
* @author Oleg Cherednik
* @since 31.12.2023
*/
public class JacksonLocalDateTimeKeySerializer extends StdSerializer<LocalDateTime> {

private static final long serialVersionUID = 8090551111500462382L;

protected final DateTimeFormatter df;

public JacksonLocalDateTimeKeySerializer(DateTimeFormatter df) {
super(LocalDateTime.class);
this.df = df;
}

@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String fieldName = getStringFieldName(value, gen, provider);
gen.writeFieldName(fieldName);
}

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

}
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@ public void serialize(LocalTime value, JsonGenerator gen, SerializerProvider pro
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 String getStringFieldName(LocalTime value, JsonGenerator gen, SerializerProvider provider) {
return df == null ? value.toString() : df.format(value);
}

protected boolean useTimestamp(SerializerProvider provider) {
return df == null && isEnabled(provider, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import lombok.NoArgsConstructor;
import sun.util.calendar.ZoneInfo;

import java.time.ZoneId;
import java.util.TimeZone;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,20 @@

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

import com.fasterxml.jackson.annotation.JsonCreator;
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 org.testng.annotations.Test;

import java.time.LocalDateTime;
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 +43,70 @@
@Test
public class JacksonLocalDateTimeSerializerTest {

public void shouldUserSuperClassLogicWhenDateFormatIsNull() throws JsonProcessingException {
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, JacksonLocalDateTimeSerializer.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(LocalDateTime.parse("2023-12-10T19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localDateTime\":\"2023-12-10T19:22:40.758927\"}}");
}

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

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

String json = mapper.writeValueAsString(new Data(LocalDateTime.parse("2023-12-10T19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localDateTime\":[2023,12,10,19,22,40,758927000]}}");
}

public void shouldUseDateFormatWhenDateFormatNotNull() throws JsonProcessingException {
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'ss:MM:yyyy");
SimpleModule module = createModule(df);

ObjectMapper mapper = new ObjectMapper().registerModule(module);
String json = mapper.writeValueAsString(LocalDateTime.parse("2017-07-23T13:57:14.225"));
assertThat(json).isEqualTo("[2017,7,23,13,57,14,225000000]");

String json = mapper.writeValueAsString(new Data(LocalDateTime.parse("2023-12-10T19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"localDateTime\":\"10-12-2023T40:12:2023\"}}");
}

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

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

private final Map<String, LocalDateTime> map;

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

private Data(LocalDateTime value) {
this(Collections.singletonMap("localDateTime", value));
}

}


// public void shouldUserSuperClassLogicWhenDateFormatIsNull() throws JsonProcessingException {
// SimpleModule module = new SimpleModule();
// module.addSerializer(LocalDateTime.class, JacksonLocalDateTimeSerializer.INSTANCE);
//
// ObjectMapper mapper = new ObjectMapper().registerModule(module);
// String json = mapper.writeValueAsString(LocalDateTime.parse("2017-07-23T13:57:14.225"));
// assertThat(json).isEqualTo("[2017,7,23,13,57,14,225000000]");
// }

}
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,4 @@ private Data(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]");
// }

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* 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.annotation.JsonCreator;
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 org.testng.annotations.Test;

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

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

/**
* @author Oleg Cherednik
* @since 31.12.2023
*/
@Test
@SuppressWarnings("NewClassNamingConvention")
public class JacksonLocalDateTimeKeySerializerTest {

public void shouldUseToStringWhenDateFormatIsNull() throws JsonProcessingException {
SimpleModule module = createModule(null);
ObjectMapper mapper = new ObjectMapper().registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalDateTime.parse("2023-12-10T19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"2023-12-10T19:22:40.758927\":\"localDateTime\"}}");
}

public void shouldUseDateFormatWhenDateFormatNotNull() throws JsonProcessingException {
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'ss:MM:yyyy");
SimpleModule module = createModule(df);

ObjectMapper mapper = new ObjectMapper().registerModule(module);

String json = mapper.writeValueAsString(new Data(LocalDateTime.parse("2023-12-10T19:22:40.758927")));
assertThat(json).isEqualTo("{\"map\":{\"10-12-2023T40:12:2023\":\"localDateTime\"}}");
}

private static SimpleModule createModule(DateTimeFormatter df) {
SimpleModule module = new SimpleModule();
module.addKeySerializer(LocalDateTime.class, new JacksonLocalDateTimeKeySerializer(df));
return module;
}

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

private final Map<LocalDateTime, String> map;

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

private Data(LocalDateTime key) {
this(Collections.singletonMap(key, "localDateTime"));
}

}

}

0 comments on commit e0633b5

Please sign in to comment.