Spring @RestController自定义JSON反序列化器
我想对某些类使用自定义JSON反序列化器(在此处 ),但无法正常工作。自定义解串器只是不被调用。
我使用Spring Boot 1.2。
解串器:
public class ModelDeserializer extends JsonDeserializer<Role> { @Override
public Role deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return null; // this is what should be called but it isn't
}
}
控制器:
@RestControllerpublic class RoleController {
@RequestMapping(value = "/role", method = RequestMethod.POST)
public Object createRole(Role role) {
// ... this is called
}
}
@JsonDeserialize
在角色上@JsonDeserialize(using = ModelDeserializer.class)
public class Role extends Model {
}
Jackson2ObjectMapperBuilder
Java Config中的bean@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.deserializerByType(Role.class, new ModelDeserializer());
return builder;
}
我究竟做错了什么?
可能是@RestController
由于它与@Controller
…
回答:
首先,您不需要重写Jackson2ObjectMapperBuilder
即可添加自定义反序列化器。当您无法添加@JsonDeserialize
注释时,应使用此方法。您应该使用@JsonDeserialize
或覆盖Jackson2ObjectMapperBuilder
。
缺少的是@RequestBody
注释:
@RestControllerpublic class JacksonCustomDesRestEndpoint {
@RequestMapping(value = "/role", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Object createRole(@RequestBody Role role) {
return role;
}
}
@JsonDeserialize(using = RoleDeserializer.class)
public class Role {
// ......
}
public class RoleDeserializer extends JsonDeserializer<Role> {
@Override
public Role deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// .................
return something;
}
}
以上是 Spring @RestController自定义JSON反序列化器 的全部内容, 来源链接: utcz.com/qa/424580.html