如何为 json 反序列化编写 initbinder?

How to write initbinder for json deserialization?

我有以下 POJO:

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

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

当我从表单接受(构造)对象以正确地将 String 转换为 HttpStatus 时,我写了 InitBinder:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(HttpStatus.class, new PropertyEditorSupport() {
        public void setAsText(String code) {
            if (StringUtils.isNotBlank(code)) {
                setValue(HttpStatus.valueOf(Integer.parseInt(code)));
            }
        }
    });

形式很酷。

我也有接受 json:

的控制器方法
@RequestMapping(value = "sendData.json", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8",
            headers = "content-type=application/x-www-form-urlencoded")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void putJsonData(@RequestBody MyClass myClass) {
        ....
    }

我这样传递 httpStatus:

...
"HttpStatus":500
...

但它转换不正确,我看到以下错误消息:

Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read JSON: Can not construct instance of org.springframework.http.HttpStatus from number value (500): index value outside legal index range [0..65]\n

据我了解,它转换不正确。

如何自定义此流程?

问题是这样解决的:

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