Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Groovy Jackson Deserializer to convert a .NET style JSON dateTime to a Java LocalDateTime object
class JsonDotNetLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
LocalDateTime deserialize(JsonParser parser, DeserializationContext ctxt) {
convertDotNetDateToJava(parser.text.trim())
}
/**
* Returns a Java LocalDateTime when given a .Net Date String
* /Date(1535491858840-0500)/
*/
static LocalDateTime convertDotNetDateToJava(String dotNetDate) {
// Strip the prefix and suffix to just 1535491858840-0500
String epochAndOffset = dotNetDate[6..-3]
// 1535491858840
String epoch = epochAndOffset[0..-6]
// -0500 Note, keep the negative/positive indicator
String offset = epochAndOffset[-5..-1]
ZoneId zoneId = ZoneId.of("UTC${offset}")
LocalDateTime.ofInstant(Instant.ofEpochMilli(epoch.toLong()), zoneId)
}
}
//Yeah imports at bottom are weird, but avoids them cluttering the gist
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
class JsonDotNetLocalDateTimeDeserializerSpec extends Specification {
@Unroll
def "test convertDotNetDateToJava for #dotNetDate"(String dotNetDate, String expected) {
expect:
convertDotNetDateToJava(dotNetDate) == LocalDateTime.parse(expected)
where:
dotNetDate || expected
'/Date(1535491858840-0500)/' || '2018-08-28T16:30:58.840'
'/Date(1535491858840+0500)/' || '2018-08-29T02:30:58.840'
'/Date(1535491858840-0000)/' || '2018-08-28T21:30:58.840'
'/Date(1535491858840-0430)/' || '2018-08-28T17:00:58.840'
}
}
import spock.lang.Specification
import spock.lang.Unroll
import java.time.LocalDateTime
import static JsonDotNetLocalDateTimeDeserializer.convertDotNetDateToJava
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.