I am using the Spring Framework, version 4.1.6, with Spring web services and without Spring Boot. To learn the framework, I am writing a REST API and am testing to make sure that the JSON response received from hitting an endpoint is correct. Specifically, I am trying to adjust the ObjectMapper
's PropertyNamingStrategy
to use the "lower case with underscores" naming strategy.
I am using the method detailed on Spring's blog to create a new ObjectMapper
and add it to the list of converters. This is as follows:
package com.myproject.config; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import org.springframework.context.annotation.*; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { Jackson2ObjectMapperBuilder builder = jacksonBuilder(); converters.add(new MappingJackson2HttpMessageConverter(builder.build())); } public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); return builder; } }
Then I run the following test (using JUnit, MockMvc, and Mockito) to verify my changes:
package com.myproject.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.AnnotationConfigWebContextLoader; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; // Along with other application imports... @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = {WebConfig.class}, loader = AnnotationConfigWebContextLoader.class) public class MyControllerTest { @Mock private MyManager myManager; @InjectMocks private MyController myController; private MockMvc mockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(this.myController).build(); } @Test public void testMyControllerWithNameParam() throws Exception { MyEntity expected = new MyEntity(); String name = "expected"; String title = "expected title"; // Set up MyEntity with data. expected.setId(1); // Random ID. expected.setEntityName(name); expected.setEntityTitle(title) // When the MyManager instance is asked for the MyEntity with name parameter, // return expected. when(this.myManager.read(name)).thenReturn(expected); // Assert the proper results. MvcResult result = mockMvc.perform( get("/v1/endpoint") .param("name", name)) .andExpect(status().isOk()) .andExpect((content().contentType("application/json;charset=UTF-8"))) .andExpect(jsonPath("$.entity_name", is(name)))) .andExpect(jsonPath("$.entity_title", is(title))) .andReturn(); System.out.println(result.getResponse().getContentAsString()); } }
However, this returns a response of:
{"id": 1, "entityName": "expected", "entityTitle": "expected title"}
When I should get:
{"id": 1, "entity_name": "expected", "entity_title": "expected title"}
I have an implemented WebApplicationInitializer that scans for the package:
package com.myproject.config; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; public class WebAppInitializer implements WebApplicationInitializer { public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.scan("com.myproject.config"); ctx.setServletContext(servletContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); servletContext.addListener(new ContextLoaderListener(ctx)); } }
Using my debugger within IntelliJ, I can see that the builder is created and added, but somewhere down the line the resulting ObjectMapper
is not actually used. I must be missing something, but all the examples I've managed to find don't seem to mention what that is! I've tried eliminating @EnableWebMvc
and implementing WebMvcConfigurationSupport
, using MappingJackson2HttpMessageConverter
as a Bean, and setting ObjectMapper
as a Bean to no avail.
Any help would be greatly appreciated! Please let me know if any other files are required.
Thanks!
EDIT: Was doing some more digging and found this. In the link, the author appends setMessageConverters()
before he/she builds MockMvc and it works for the author. Doing the same worked for me as well; however, I'm not sure if everything will work in production as the repositories aren't flushed out yet. When I find out I will submit an answer.
EDIT 2: See answer.
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.
Overview. When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this tutorial, we'll take a look at the most common ways to configure the serialization and deserialization options. To learn more about Jackson, be sure to check out our Jackson tutorial.
If you're working with Spring Boot, there's a section in the manual dedicated to working with the ObjectMapper If you create a default Jackson2ObjectMapperBuilder @Bean , you should be able to autowire that same ObjectMapper instance in your controller.
Spring Framework and Spring Boot provide builtin support for Jackson based XML serialization/deserialization. As soon as you include the jackson-dataformat-xml dependency to your project, it is automatically used instead of JAXB2.
I looked into understanding why this works the way that it did. To reiterate, the process of getting my customized ObjectMapper to work in my test (assuming MockMvc is being created as a standalone) is as follows:
WebConfig
class that extends WebMvcConfigurerAdapter
.WebConfig
class, create a new @Bean
that returns a MappingJackson2HttpMessageConverter
. This MappingJackson2HttpMessageConverter
has the desired changes applied to it (in my case, it was passing it a Jackson2ObjectMapperBuilder
with the PropertyNamingStrategy
set to CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
.)WebConfig
class, @Override
configureMessageConverters()
and add the MappingJackson2HttpMessageConverter
from (2) to the list of message converters.@ContextConfiguration(classes = { WebConfig.class })
annotation to inform the test of your @Bean
.@Autowired
to inject and access the @Bean
defined in (2).MockMvc
, use the .setMessageConverters()
method and pass it the injected MappingJackson2HttpMessageConverter
. The test will now use the configuration set in (2).The test file:
package com.myproject.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.AnnotationConfigWebContextLoader; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; // Along with other application imports... @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = {WebConfig.class}) public class MyControllerTest { /** * Note that the converter needs to be autowired into the test in order for * MockMvc to recognize it in the setup() method. */ @Autowired private MappingJackson2HttpMessageConverter jackson2HttpMessageConverter; @Mock private MyManager myManager; @InjectMocks private MyController myController; private MockMvc mockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders .standaloneSetup(this.myController) .setMessageConverters(this.jackson2HttpMessageConverter) // Important! .build(); } @Test public void testMyControllerWithNameParam() throws Exception { MyEntity expected = new MyEntity(); String name = "expected"; String title = "expected title"; // Set up MyEntity with data. expected.setId(1); // Random ID. expected.setEntityName(name); expected.setEntityTitle(title) // When the MyManager instance is asked for the MyEntity with name parameter, // return expected. when(this.myManager.read(name)).thenReturn(expected); // Assert the proper results. MvcResult result = mockMvc.perform( get("/v1/endpoint") .param("name", name)) .andExpect(status().isOk()) .andExpect((content().contentType("application/json;charset=UTF-8"))) .andExpect(jsonPath("$.entity_name", is(name)))) .andExpect(jsonPath("$.entity_title", is(title))) .andReturn(); System.out.println(result.getResponse().getContentAsString()); } }
And the configuration file:
package com.myproject.config; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import org.springframework.context.annotation.*; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(jackson2HttpMessageConverter()); } @Bean public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); Jackson2ObjectMapperBuilder builder = this.jacksonBuilder(); converter.setObjectMapper(builder.build()); return converter; } public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); return builder; } }
Deploying my generated WAR file to Tomcat 7 in XAMPP shows that the naming strategy is being used correctly. The reason I believe that this works the way that it does is because with a standalone setup, a default set of message converters is always used unless otherwise specified. This can be seen in the comment for the setMessageConverters()
function within StandAloneMockMvcBuilder.java (version 4.1.6, \org\springframework\test\web\servlet\setup\StandaloneMockMvcBuilder.java
):
/** * Set the message converters to use in argument resolvers and in return value * handlers, which support reading and/or writing to the body of the request * and response. If no message converters are added to the list, a default * list of converters is added instead. */ public StandaloneMockMvcBuilder setMessageConverters(HttpMessageConverter<?>...messageConverters) { this.messageConverters = Arrays.asList(messageConverters); return this; }
Therefore, if MockMvc is not explicitly told about one's changes to the message converters during the building of the MockMvc, it will not use the changes.
or you can
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); mappingJackson2HttpMessageConverter.setObjectMapper( new ObjectMapper().setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) ); mockMvc = MockMvcBuilders.standaloneSetup(attributionController).setMessageConverters( mappingJackson2HttpMessageConverter ).build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With