Spring @RestController custom JSON deserializer
31,507
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
.
What is missed is the @RequestBody
annotation:
@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;
}
}
Author by
jakub.petr
Updated on December 02, 2020Comments
-
jakub.petr over 3 years
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.
I use Spring Boot 1.2.
Deserializer:
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 } }
Controller:
@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
bean in Java Config@Bean public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.deserializerByType(Role.class, new ModelDeserializer()); return builder; }
What am I doing wrong?
EDIT It is probably caused by
@RestController
because it works with@Controller
... -
Hector about 7 yearsI need to do the same, the only difference is that I have a get method and in my pojo object I use a Date type with @JsonDeserialize, but when I run the method I get an http 400. (spring 4.1.7 y jackson 2.7.4)