Skip to content

Commit

Permalink
Merge pull request #457 from scireum/feature/sbi/SIRI-736
Browse files Browse the repository at this point in the history
Properly serializes and deserializes dates and times in JSON
  • Loading branch information
sabieber committed May 15, 2023
2 parents 1d7ebf6 + a5f3df7 commit dbf4854
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 10 deletions.
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- Required, as the version provided by docker-compose-rule-core has security issues -->
<dependency>
<groupId>org.yaml</groupId>
Expand Down
28 changes: 27 additions & 1 deletion src/main/java/sirius/kernel/commons/Json.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.Log;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
Expand Down Expand Up @@ -54,7 +57,9 @@ public class Json {
*/
public static final ObjectMapper MAPPER =
new ObjectMapper().configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.registerModule(new JavaTimeModule());

private Json() {
}
Expand Down Expand Up @@ -564,6 +569,27 @@ public static Amount getValueAmount(@Nonnull JsonNode jsonNode, String fieldName
return Amount.NOTHING;
}

/**
* Tries to read a {@link LocalDate} value from the given {@link JsonNode} at the given field name. JSON does
* not define a date format, so we fall back to ISO-8601.
*
* @param jsonNode the node to retrieve the value from
* @param fieldName the field name of the value to retrieve
* @return the value at the given field name or an empty optional if the field does not exist or the node is null
*/
@Nonnull
public static Optional<LocalDate> tryValueDate(@Nonnull JsonNode jsonNode, String fieldName) {
JsonNode node = jsonNode.get(fieldName);
if (node == null || node.isNull() || !node.isTextual()) {
return Optional.empty();
}
try {
return Optional.of(LocalDate.parse(node.textValue(), DateTimeFormatter.ISO_DATE));
} catch (DateTimeParseException exception) {
return Optional.empty();
}
}

/**
* Tries to read a {@link LocalDateTime} value from the given {@link JsonNode} at the given field name. JSON does
* not define a date format, so we fall back to ISO-8601 which is the default format e.g. used from
Expand Down
36 changes: 27 additions & 9 deletions src/test/kotlin/sirius/kernel/commons/JsonTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
import kotlin.test.assertEquals
Expand All @@ -41,7 +42,7 @@ class JsonTest {

@Test
fun `valid object is parsed properly`() {
val json = """{ "foo": 123, "bar": "baz" }"""
val json = """{"foo":123,"bar":"baz"}"""
val node = Json.parseObject(json)
assertEquals(2, node.size())
assertEquals(123, node["foo"].asInt())
Expand Down Expand Up @@ -85,9 +86,15 @@ class JsonTest {

@Test
fun `valid object is written properly`() {
val node = Json.createObject().put("foo", 123).put("bar", "baz")
val date = LocalDate.now()
val time = LocalDateTime.now()
val node = Json.createObject()
.put("foo", 123)
.put("bar", "baz")
.putPOJO("date", date)
.putPOJO("time", time)
val json = Json.write(node)
assertEquals("""{"foo":123,"bar":"baz"}""", json)
assertEquals("""{"foo":123,"bar":"baz","date":"$date","time":"$time"}""", json)
}

@Test
Expand Down Expand Up @@ -316,13 +323,24 @@ class JsonTest {
}

@Test
fun `tryValueDateTime reads JS Date stringify representation aka ISO-8601 from strings`() {
val json = """{ "jsJsonStringifyDate": "2023-05-10T09:00:00.000Z" }"""
val node = Json.parseObject(json)
fun `dates and times can be read properly`() {

// JS Date stringify representation aka ISO-8601 from strings
val jsJson = """{ "jsJsonStringifyDate": "2023-01-01T13:37:00.000Z" }"""
val jsNode = Json.parseObject(jsJson)

val expectedJsDateTime = LocalDateTime.of(2023, 1, 1, 13, 37, 0, 0)
assertEquals(expectedJsDateTime, Json.tryValueDateTime(jsNode, "jsJsonStringifyDate").get())
assertTrue(Json.tryValueDateTime(jsNode, "missingNode").isEmpty)

// ISO-8601 String representations like generated via Json.write (Jackson -> Jackson)
val jacksonJson = """{"date":"2023-01-01","time":"2023-01-01T13:37:00.123456"}"""
val jacksonNode = Json.parseObject(jacksonJson)

val expected = LocalDateTime.of(2023, 5, 10, 9, 0, 0)
assertEquals(expected, Json.tryValueDateTime(node, "jsJsonStringifyDate").get())
assertTrue(Json.tryValueDateTime(node, "missingNode").isEmpty)
val expectedJacksonDate = LocalDate.of(2023, 1, 1)
val expectedJacksonDateTime = LocalDateTime.of(2023, 1, 1, 13, 37, 0, 123456000)
assertEquals(expectedJacksonDate, Json.tryValueDate(jacksonNode, "date").get())
assertEquals(expectedJacksonDateTime, Json.tryValueDateTime(jacksonNode, "time").get())
}

@Test
Expand Down

0 comments on commit dbf4854

Please sign in to comment.