问题描述
我想为某些类使用自定义JSON反序列化器(角色),但我无法使其正常工作。自定义反序列化器不会被调用。
I want to use custom JSON deserializer for some classes(Role here) but I can't get it working. The custom deserializer just isn't called.
我使用Spring Boot 1.2。
I use 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
}
}
控制器:
@RestController
public class RoleController {
@RequestMapping(value = "/role", method = RequestMethod.POST)
public Object createRole(Role role) {
// ... this is called
}
}
-
@JsonDeserialize
on Role
@JsonDeserialize(using = ModelDeserializer.class)
public class Role extends Model {
}
Jackson2ObjectMapperBuilder
Java Config中的bean
Jackson2ObjectMapperBuilder
bean in Java Config
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.deserializerByType(Role.class, new ModelDeserializer());
return builder;
}
我在做什么错误?
编辑这可能是由 @RestController
引起的,因为它适用于 @Controller
...
EDIT It is probably caused by @RestController
because it works with @Controller
...
推荐答案
首先你不需要覆盖 Jackson2ObjectMapperBuilder
以添加自定义反序列化器。当您无法添加 @JsonDeserialize
注释时,应使用此方法。你应该使用 @JsonDeserialize
或覆盖 Jackson2ObjectMapperBuilder
。
First of all you don't need to override Jackson2ObjectMapperBuilder
to add custom deserializer. This approach should be used when you can't add @JsonDeserialize
annotation. You should use @JsonDeserialize
or override Jackson2ObjectMapperBuilder
.
遗漏的是 @RequestBody
注释:
@RestController
public 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反序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!