Add locale customization of the ObjectMapper

Add a new spring.jackson.locale property to customize the locale of the
ObjectMapper.

Closes gh-3600
pull/3598/merge
Johannes Stelzer 9 years ago committed by Stephane Nicoll
parent 4c5a1036a3
commit 64461bb978

@ -162,6 +162,7 @@ public class JacksonAutoConfiguration {
configureDateFormat(builder);
configurePropertyNamingStrategy(builder);
configureModules(builder);
configureLocale(builder);
return builder;
}
@ -237,6 +238,13 @@ public class JacksonAutoConfiguration {
builder.modulesToInstall(moduleBeans.toArray(new Module[moduleBeans.size()]));
}
private void configureLocale(Jackson2ObjectMapperBuilder builder) {
String locale = this.jacksonProperties.getLocale();
if (locale != null) {
builder.locale(locale);
}
}
private static <T> Collection<T> getBeans(ListableBeanFactory beanFactory,
Class<T> type) {
return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type)

@ -95,6 +95,11 @@ public class JacksonProperties {
*/
private TimeZone timeZone = null;
/**
* Locale used for formatting.
*/
private String locale;
public String getDateFormat() {
return this.dateFormat;
}
@ -155,4 +160,12 @@ public class JacksonProperties {
this.timeZone = timeZone;
}
public String getLocale() {
return this.locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
}

@ -381,6 +381,7 @@ public class JacksonAutoConfigurationTests {
"spring.jackson.time-zone:America/Los_Angeles");
EnvironmentTestUtils.addEnvironment(this.context,
"spring.jackson.date-format:zzzz");
EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.locale:en");
this.context.refresh();
ObjectMapper objectMapper = this.context.getBean(
Jackson2ObjectMapperBuilder.class).build();
@ -402,6 +403,21 @@ public class JacksonAutoConfigurationTests {
assertEquals("\"GMT+10:00\"", objectMapper.writeValueAsString(date));
}
@Test
public void customLocale() throws JsonProcessingException {
this.context.register(JacksonAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.locale:de");
EnvironmentTestUtils.addEnvironment(this.context,
"spring.jackson.date-format:zzzz");
this.context.refresh();
ObjectMapper objectMapper = this.context
.getBean(Jackson2ObjectMapperBuilder.class).build();
DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC);
assertEquals("\"Koordinierte Universalzeit\"",
objectMapper.writeValueAsString(dateTime));
}
@Configuration
protected static class MockObjectMapperConfig {

Loading…
Cancel
Save