簡體   English   中英

如何編寫用於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;
    }
    ....
}

當我從表單接受(construct)對象以將String正確轉換為InitBinder我已經寫了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()));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM