如何从杰克逊的数组中自定义反序列化?

时间:2016-01-05 20:39:56

标签: java json serialization jackson

我想将(Joda)日期序列化/反序列化为数组。

不幸的是,我无法弄清楚如何进行deserializtion部分:

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;

import java.io.IOException;

public class TryJodaTime {

   public static class LocalTimeSerializer extends JsonSerializer<LocalTime> {

      @Override
      public void serialize(LocalTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {

         gen.writeStartArray();
         gen.writeNumber(value.getHourOfDay());
         gen.writeNumber(value.getMinuteOfHour());
         gen.writeNumber(value.getSecondOfMinute());
         gen.writeNumber(value.getMillisOfSecond());

         gen.writeEndArray();

      }
   }

   public static class LocalTimeDeserializer extends JsonDeserializer<LocalTime> {

      @Override
      public LocalTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

         JsonToken token;

         token = jp.nextToken();
         if( token != JsonToken.START_ARRAY ) {
            throw new JsonParseException("Start array expected", jp.getCurrentLocation());
         }

         int hour = jp.nextIntValue(0);
         int minute = jp.nextIntValue(0);
         int second = jp.nextIntValue(0);
         int ms = jp.nextIntValue(0);

         token = jp.nextToken();
         if( token != JsonToken.END_ARRAY ) {
            throw new JsonParseException("End array expected", jp.getCurrentLocation());
         }

         return new LocalTime(hour, minute, second, ms);
      }
   }


   public static class MyClass {

      private LocalTime localTime;

      public MyClass() {
         localTime = LocalTime.now();
      }

      @JsonSerialize(using = LocalTimeSerializer.class)
      public LocalTime getLocalTime() {
         return localTime;
      }

      @JsonDeserialize(using = LocalTimeDeserializer.class)
      public void setLocalTime(LocalTime localTime) {
         this.localTime = localTime;
      }

   }

   public static void main(String[] args) throws IOException {


      MyClass myClass = new MyClass();
      ObjectMapper mapper = new ObjectMapper();
      String string = mapper.writeValueAsString(myClass);

      System.out.println(string);

      MyClass myClass2 = mapper.readValue(string, MyClass.class);

      System.out.println(myClass2.toString());


   }
}

此代码导致我自己的异常抛出

throw new JsonParseException("Start array expected", jp.getCurrentLocation());

1 个答案:

答案 0 :(得分:1)

当调用0.05000000000000000277555756156289135105907917022705078125时,Jackson已经移动到阵列令牌。换句话说,在LocalTimeDeserializer#deserialize内,deserialize的当前令牌是数组令牌。

您可以使用它来验证您正在反序列化您的期望,然后继续进行反序列化。

JsonParser