本文介绍了杰克逊 - 反序列化一个基本枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
枚举状态{
活动,
无效
}
{status:1}表示Status.Active,但杰克逊使其成为Status.Inactive:(
解决方案
您可以为您的枚举创建自定义类型的解串器:
public enum Status {
ACTIVE,
INACTIVE;
public static StatusTypeType(final int typeCode){
switch(typeCode){
case 1:return ACTIVE;
case 2:return INACTIVE;
}
throw new IllegalArgumentException(Invalid Status type code:+ typeCode) ;
}
}
public class StatusDeserializer扩展JsonDeserializer< Status> {
@Override
public Status deserialize(final JsonParser parser,final DeserializationContext context) throws IOException {
return Status.fromTypeC ODE(parser.getValueAsInt());
}
}
然后,您可以告诉杰克逊使用您的自定义解串器一个属性:
public class WarpDrive {
private Status status;
@JsonDeserialize(using = StatusDeserializer.class)
public void setStatus(final Status status){
this.status = status;
}
public Status getStatus(){
return this.status;
}
}
您还可以将Jackson对象映射器配置为使用针对目标类型的所有出现的自定义反序列化程序。请参阅。
is it possible to deserialize enums, which have a one based index?
enum Status {
Active,
Inactive
}
{status:1} means Status.Active, but Jackson makes it Status.Inactive :(
解决方案
You can create a custom type deserialiser for your enum:
public enum Status {
ACTIVE,
INACTIVE;
public static Status fromTypeCode(final int typeCode) {
switch(typeCode) {
case 1: return ACTIVE;
case 2: return INACTIVE;
}
throw new IllegalArgumentException("Invalid Status type code: " + typeCode);
}
}
public class StatusDeserializer extends JsonDeserializer<Status> {
@Override
public Status deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
return Status.fromTypeCode(parser.getValueAsInt());
}
}
You can then tell Jackson to use your custom deserialiser for a property:
public class WarpDrive {
private Status status;
@JsonDeserialize(using = StatusDeserializer.class)
public void setStatus(final Status status) {
this.status = status;
}
public Status getStatus() {
return this.status;
}
}
You can also configure the Jackson object mapper to use your custom deserialiser for all occurrences of the target type. See http://wiki.fasterxml.com/JacksonHowToCustomDeserializers.
这篇关于杰克逊 - 反序列化一个基本枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!