如何为不同的场景使用不同的解串器。
例如
public class Student {
@JsonDeserialize(using = SomeAdeserializer.class)
@JsonProperty("dob")
Date dateOfBirth;
}
如何使用不同的反序列化器,例如SomeBdeserializer.class来反序列化我的数据?
答案 0 :(得分:1)
一个选项是让一个反序列化器根据一些上下文信息在运行时选择去除化合物格式。可以在deserilize方法内部进行选择,也可以将反序列化委托给另一个解串器。
另一种选择是在两个不同的对象映射器中为相同类型注册两个不同的反序列化器(link)。然后根据上下文在运行时选择对象映射器。这是一个例子:
public class JacksonTwoDeserilizers {
public static class Bean {
public final Date date;
@JsonCreator
public Bean(@JsonProperty("date") Date date) {
this.date = date;
}
@Override
public String toString() {
return "Bean{" +
"date=" + date +
'}';
}
}
public static class DateDeserializer extends StdDeserializer<Date> {
private final int hours;
protected DateDeserializer(int hours) {
super(Date.class);
this.hours = hours;
}
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
Date date = this._parseDate(jp, ctxt);
return new Date(date.getTime() + 1000 * 60 * 60 * hours);
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper1 = new ObjectMapper();
ObjectMapper mapper2 = new ObjectMapper();
SimpleModule module1 = new SimpleModule();
SimpleModule module2 = new SimpleModule();
module1.addDeserializer(Date.class, new DateDeserializer(6));
mapper1.registerModule(module1);
module2.addDeserializer(Date.class, new DateDeserializer(12));
mapper2.registerModule(module2);
long currentTimeMillis = System.currentTimeMillis();
System.out.println(new Date(currentTimeMillis));
String json = "{\"date\":" + currentTimeMillis + "}";
System.out.println("Mapper1: " + mapper1.readValue(json, Bean.class));
System.out.println("Mapper2: " + mapper2.readValue(json, Bean.class));
}
}
输出:
Sat May 24 12:06:25 CEST 2014
Bean{date=Sat May 24 18:06:25 CEST 2014}
Bean{date=Sun May 25 00:06:25 CEST 2014}