0

我有以下 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;
    }
    ....
}

当我从表单接受(构造)对象以正确将字符串转换为 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

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

如何自定义此过程?

4

1 回答 1

1

问题是这样解决的:

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()));
    }
}
于 2015-07-31T20:58:04.187 回答