如何为第三方枚举自定义反序列化器?

时间:2015-07-31 13:56:18

标签: java spring spring-mvc jackson deserialization

我有以下deseriailzer:

public class HttpStatusDeserializer extends JsonDeserializer<HttpStatus> {

    @Override
    public HttpStatus deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return HttpStatus.valueOf(node.asText());
    }
}

并注册

public class CustomDeserializerModifier extends BeanDeserializerModifier {

    @Override
    public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
        if (beanDesc.getBeanClass() == HttpStatus.class) {
            return new HttpStatusDeserializer();
        }
        return deserializer;

    }
}
 mappingJackson2HttpMessageConverter
                .setObjectMapper(new ObjectMapper().registerModule(new SimpleModule()
                                                                           .setSerializerModifier(new CustomSerializerModifier())
                                                                           .setDeserializerModifier(new CustomDeserializerModifier())));

它不会为枚举调用,而是为其他类调用。

我怎样才能赢得这个?

1 个答案:

答案 0 :(得分:0)

问题解决了这样:

class MyClass{
    ...
    HttpStatus httpStatus = HttpStatus.OK //from org.springframework.http
    @JsonIgnore
    public HttpStatus getHttpStatus() {
        return httpStatus;
     }

    @JsonProperty(value = "HttpStatus")
    @JsonDeserialize(using = HttpStatusDeserializer.class)
    public void setHttpStatus(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }
    ....
}

和反序列化器:

public class HttpStatusDeserializer extends JsonDeserializer<HttpStatus> {    
    @Override
    public HttpStatus deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return HttpStatus.valueOf(Integer.parseInt(node.asText()));
    }
}