As per JSON specification, I am aware that leading zeroes are not allowed in integers in JSON. But as per Jackson documentation, there is a property in Jackson library i.e.
MappingJackson2HttpMessageConverter
by default uses Jackson2ObjectMapperBuilder
class to build new instance of ObjectMapper
class. To override and use ObjectMapper
from container we need to override JSON
converter:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
@Configuration
public class JacksonMvcConfiguration extends WebMvcConfigurationSupport {
@Autowired
private ObjectMapper objectMapper;
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
return converter;
}
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
}
See Customizing HttpMessageConverters with Spring Boot and Spring MVC. Since now you should be able to parse numbers with leading zeros.
Just a note for people that are having that issue and are looking for a newer working solution:
Import latest version of fasterxml jackson in maven (2.11.0 as of today):
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.11.0</version>
</dependency>
Create the mapper object:
ObjectMapper objectMapper = new ObjectMapper();
Allow the leading zeros for numbers (the not deprecated version):
objectMapper.enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS.mappedFeature());
used imports:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.json.JsonReadFeature;
Keep in mind this will trim the leading 0s. If you want to keep them then your json value shouldn't be a numeric.
Simply put following property on your application.properties
file
spring.jackson.parser.allow-numeric-leading-zeros=true
You can set jackson as default converter by following property if not set default
spring.http.converters.preferred-json-mapper=jackson
This is most likely due to ObjectMapper
that Spring endpoint uses being configured different from mapper being injected into field.
Why this is I can't say -- maybe Spring users list could help.