gpt4 book ai didi

java - 如何编写initbinder进行json反序列化?

转载 作者:行者123 更新时间:2023-12-01 11:16:40 26 4
gpt4 key购买 nike

我有以下 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 的 Controller 方法:

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

关于java - 如何编写initbinder进行json反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31744897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com