Jackson Data Binding for LocalDate[] using annotation

1.8k views Asked by At

I am converting a JSON file into Java object using Jackson with Java 8 Module. But while converting JSON array to LocalDate[] application is throwing an exception.

How to convert below JSON array to LocalDate[] using annotations?

JSON

{
    "skip": [
        "01/01/2019",
        "26/01/2019"
    ]
}

Code

@JsonFormat(pattern = "dd/MM/yyyy")
@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate[] skip;

Exception

com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (VALUE_STRING) within Array, expected VALUE_NUMBER_INT
 at [Source: (ByteArrayInputStream); line: 25, column: 3] (through reference chain: com.saalamsaifi.springwfrlroster.model.Team["skip"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer.deserialize(LocalDateDeserializer.java:110)
    at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer.deserialize(LocalDateDeserializer.java:38)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3070)
3

There are 3 answers

2
Utku Özdemir On BEST ANSWER

Since skip is of type array, LocalDateSerializer, LocalDateDeserializer and JsonFormat do not work out of the box - they are implemented to expect direct value tokens and not arrays.

You can implement your own serializer/deserializers. A naive deserializer I implemented to deserialize your example is the following:

public class CustomLocalDateArrayDeserializer extends JsonDeserializer<LocalDate[]> {

  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

  @Override
  public LocalDate[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    ArrayList<LocalDate> list = new ArrayList<>();
    JsonToken currentToken = p.getCurrentToken();
    if (currentToken != JsonToken.START_ARRAY) {
      throw new JsonMappingException(p, "Not an array!");
    }

    currentToken = p.nextToken();

    while (currentToken != JsonToken.END_ARRAY) {
      if (currentToken != JsonToken.VALUE_STRING) {
        throw new JsonMappingException(p, "Not a string element!");
      }

      LocalDate localDate = LocalDate.parse(p.getValueAsString(), formatter);
      list.add(localDate);

      currentToken = p.nextToken();
    }

    return list.toArray(new LocalDate[0]);
  }
}

And I changed the field annotation to be @JsonDeserialize(using = CustomLocalDateArrayDeserializer.class).

You can work on it to iterate & improve over it, make it read&respect @JsonFormat annotation and so on, if you think it is worth the effort.

0
digitalized On

Just first glance: are actually json objects in your json array or just Strings as you showed? This should be something like this: { "skip": [ "key1":"01/01/2019", "key2":"26/01/2019" ] }

0
D. Beer On

I suspect looking at your code and your json model it is trying to convert to an array using a deserializer that is defined for one object. It simple terms you are trying to convert a single item to an array which it cant parse. You could Try a list of LocalDate instead. Something Like:

List<LocalDate> skip;

You might even need to create your own Deserializer based on the date serializer.