How to convert all keys in JSON response to uppercase? (JAVA)

戏子无情 提交于 2019-12-11 01:17:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!