I
I
Igor2020-07-05 15:51:04
Spring
Igor, 2020-07-05 15:51:04

How to make a different string deserializer for different handles in Spring?

Problem: empty strings ("") arrive in the request, as well as those consisting of only spaces.
Googled, added a simple deserializer to the config:

@Bean(name = JACKSON_MAPPER_BEAN_NAME)
    public ObjectMapper objectMapper(StatusNameResolver resolver) {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule blankStringModule = new SimpleModule();

        blankStringModule.addDeserializer(
                String.class,
                new StdDeserializer<String>(String.class) {

                    @Override
                    public String deserialize(JsonParser parser, DeserializationContext context)
                            throws IOException {
                        String result = StringDeserializer.instance.deserialize(parser, context);
                        if (StringUtils.isBlank(result)) {
                            return null;
                        }
                        return result;
                    }
                });

        objectMapper.registerModule(blankStringModule);
        return objectMapper;
    }


The problem seemed to be gone, but in other requests everything broke down, since there this solution turned out to be unexpected.

Question: how to do the same, but for one specific method of the REST controller?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question