问题
For example I have the following json response :
{
StaTuS:succees,
LanGuaGes: {
Key1: English,
key2: Spanish,
kEy3: Indian
}
}
The response can have many nested elements. I want to know how we can code in such a way that all the keys can be converted to uppercase in my response so that it matches the naming convention I used in my POJO class.
Like this :
{
STATUS:succees,
LANGUAGES: {
KEY1: English,
KEY2: Spanish,
KEY3: Indian
}
}
回答1:
You can use a custom PropertyNamingStrategy:
public class UpperCaseStrategy extends PropertyNamingStrategyBase {
@Override
public String translate(String propertyName) {
return propertyName.toUpperCase();
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(new CustomNamingStrategy());
See here for reference.
As a note a lower case strategy is implemented in com.fasterxml.jackson.databind.PropertyNamingStrategy
as follows:
/**
* Simple strategy where external name simply only uses lower-case characters,
* and no separators.
* Conversion from internal name like "someOtherValue" would be into external name
* if "someothervalue".
*
* @since 2.4
*/
public static class LowerCaseStrategy extends PropertyNamingStrategyBase
{
@Override
public String translate(String input) {
return input.toLowerCase();
}
}
来源:https://stackoverflow.com/questions/34677874/how-to-convert-all-keys-in-json-response-to-uppercase-java