Add support for sorting json keys

Add `jsonSortKeys` property to HttpMapperProperties.

Fixes gh-498
This commit is contained in:
Piotr Maj 2014-03-14 21:36:49 -07:00 committed by Phillip Webb
parent ca0a12cedb
commit 2e74251d1b
3 changed files with 23 additions and 2 deletions

View File

@ -21,11 +21,16 @@ import org.springframework.http.converter.HttpMessageConverter;
/**
* Configuration properties to configure {@link HttpMessageConverter}s.
*
* @author Dave Syer
* @author Piotr Maj
*/
@ConfigurationProperties(name = "http.mappers", ignoreUnknownFields = false)
public class HttpMapperProperties {
private boolean jsonPrettyPrint = false;
private boolean jsonPrettyPrint;
private boolean jsonSortKeys;
public void setJsonPrettyPrint(boolean jsonPrettyPrint) {
this.jsonPrettyPrint = jsonPrettyPrint;
@ -35,4 +40,12 @@ public class HttpMapperProperties {
return this.jsonPrettyPrint;
}
public void setJsonSortKeys(boolean jsonSortKeys) {
this.jsonSortKeys = jsonSortKeys;
}
public boolean isJsonSortKeys() {
return this.jsonSortKeys;
}
}

View File

@ -38,12 +38,14 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link HttpMessageConverter}s.
*
* @author Dave Syer
* @author Christian Dupuis
* @author Piotr Maj
*/
@Configuration
@ConditionalOnClass(HttpMessageConverter.class)
@ -87,7 +89,12 @@ public class HttpMessageConvertersAutoConfiguration {
@ConditionalOnMissingBean
@Primary
public ObjectMapper jacksonObjectMapper() {
return new ObjectMapper();
ObjectMapper objectMapper = new ObjectMapper();
if (this.properties.isJsonSortKeys()) {
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,
true);
}
return objectMapper;
}
@Bean

View File

@ -64,6 +64,7 @@ server.tomcat.max-threads = 0 # number of threads in protocol handler
# SPRING MVC (HttpMapperProperties)
http.mappers.json-pretty-print=false # pretty print JSON
http.mappers.json-sort-keys=falose # sort keys
spring.view.prefix= # MVC view prefix
spring.view.suffix= # ... and suffix
spring.resources.cache-period= # cache timeouts in headers sent to browser