Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @RestController custom JSON deserializer

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
    }
}
  1. @JsonDeserialize on Role

    @JsonDeserialize(using = ModelDeserializer.class)
    public class Role extends Model {
    
    }
    
  2. 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...

like image 921
jakub.petr Avatar asked Dec 18 '14 15:12

jakub.petr


Video Answer


1 Answers

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;
    }
}
like image 62
Ilya Ovesnov Avatar answered Oct 06 '22 01:10

Ilya Ovesnov