gpt4 book ai didi

java - 如何在 Jackson 中自定义数组反序列化?

转载 作者:行者123 更新时间:2023-12-01 10:37:05 27 4
gpt4 key购买 nike

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

不幸的是,我不知道如何进行反序列化部分:

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());

最佳答案

当调用 LocalTimeDeserializer#deserialize 时,Jackson 已经移至数组 token 。换句话说,在 deserialize 中,JsonParser 的当前标记是数组标记。

您可以使用它来验证您是否正在反序列化您所期望的内容,然后继续进行反序列化:

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

关于java - 如何在 Jackson 中自定义数组反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com