如何将JSON响应中的所有键都转换为大写

如何将JSON响应中的所有键都转换为大写

本文介绍了如何将JSON响应中的所有键都转换为大写? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下json响应:

For example I have the following json response :

{
    StaTuS:succees,
    LanGuaGes: {
          Key1: English,
          key2: Spanish,
          kEy3: Indian
    }
}

响应可以包含许多嵌套元素.我想知道我们该如何编码,以便在响应中将所有键都转换为大写,从而使其与我在POJO类中使用的命名约定相匹配.

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.

喜欢这个:

{
   STATUS:succees,
   LANGUAGES: {
          KEY1: English,
          KEY2: Spanish,
          KEY3: Indian
   }
}

推荐答案

您可以使用自定义的PropertyNamingStrategy:

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());

请参见此处以供参考.

请注意,在com.fasterxml.jackson.databind.PropertyNamingStrategy中实现了一种小写策略,如下所示:

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();
    }
}

这篇关于如何将JSON响应中的所有键都转换为大写? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:00