我想对某些类使用自定义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 } }
控制器:
@RestController public class RoleController { @RequestMapping(value = "/role", method = RequestMethod.POST) public Object createRole(Role role) { // ... this is called } }
@JsonDeserialize 在角色上
@JsonDeserialize
@JsonDeserialize(using = ModelDeserializer.class)
public class Role extends Model {
}
Jackson2ObjectMapperBuilder Java Config中的bean
Jackson2ObjectMapperBuilder
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.deserializerByType(Role.class, new ModelDeserializer()); return builder; }
我究竟做错了什么?
编辑 可能是@RestController由于它与@Controller…
@RestController
@Controller
首先,您不需要重写Jackson2ObjectMapperBuilder即可添加自定义反序列化器。当您无法添加@JsonDeserialize注释时,应使用此方法。您应该使用@JsonDeserialize或覆盖Jackson2ObjectMapperBuilder。
缺少的是@RequestBody注释:
@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; } }