I have the Micronaut Http Client
with Kotlin
which loads data from another micro service. The date formatting from this micro service is not valid sometimes.
Example: normal pattern is dd-MM-yyyy
, but when there is no date micro service returns it as " - - "
. So, I need to skip the serialisation when date is " - - "
. I've already used @JsonDeserialize(using = "CustomDateDeserialize")
, but I couldn't make it to not deserialise the date field when the pattern is not met.
MyClient
@Get(value = ..., produces = [MediaType.APPLICATION_JSON])
@Headers(...)
fun findParcels(...) : HttpResponse<MyDTO>
MyDTO
@KotlinBuilder
data class ParcelsDTO(
@JsonProperty("property1")
val property1: String
@JsonProperty("property2")
val property2: Long
@JsonProperty("property3")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
val property3: LocalDate
@JsonProperty("property4")
val property4: BigDecimal
@JsonProperty("property5")
@JsonDeserialize(using = CustomLocalDateDeserializer::class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
val property5: LocalDate
)
MyCustomDeserializer
class CustomLocalDateDeserializer protected constructor() : StdDeserializer<LocalDate?>(LocalDate::class.java) {
@Throws(IOException::class)
override fun deserialize(parser: JsonParser, context: DeserializationContext?): LocalDate {
val node: JsonNode = parser.codec.readTree(parser)
val itemName = node.get("property5").asText()
if(!GenericValidator.isDate(itemName, "dd-MM-yyyy", true)){
//here was to set to not serialize the node
}
return LocalDateDeserializer.INSTANCE.deserialize(parser, context)
}
}
Source Json
{
[
{
"property1": "string",
"property2": 123,
"property3": "01-01-2021",
"property4": 1.20,
"property5": " - - ",
},
{
"property1": "string2",
"property2": 123,
"property3": "01-01-2021",
"property4": 1.20,
"property5": "01-01-2022",
},
]
}
Your custom deserialiser does more than it has to. You need to handle only date value. See how it should look like:
You can register it as below: