Jackson json to map and camelcase key name

后端 未结 3 1603
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 19:23

I want to convert json via jackson library to a map containing camelCase key...say...

from

{
    \"SomeKey\": \"SomeValue\",
    \"Anoth         


        
3条回答
  •  深忆病人
    2021-02-14 20:20

    The following will transform json with keys on any "case format" to using camelCased keys:

    /**
     * Convert all property keys of the specified JSON to camelCase
     */
    public static String toJsonWithCamelCasedKeys(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new SimpleModule()
          .addKeySerializer(String.class, new JsonSerializer<>() {
              @Override
              public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                  String key = CaseUtil.toCamelCase(value);
                  gen.writeFieldName(key);
              }
          })
        );
    
        try {
            Map jsonMap = objectMapper.readValue(json, new TypeReference<>() {});
            return objectMapper.writeValueAsString(jsonMap);
        } catch (Exception e) {
            throw new JsonException("Error transforming JSON", e);
        }
    }
    

    ...and a CaseUtil implementation could be something like this:

    import java.util.Arrays;
    import java.util.stream.Collectors;
    
    public class CaseUtil {
    
        public static String toCamelCase(String s) {
            if (s == null) {
                return null;
            }
            else if (s.isBlank()) {
                return "";
            }
    
            return decapitaliseFirstLetter(
              String.join("", Arrays.stream(s.split("[-_\\s]"))
              .map(CaseUtil::capitaliseFirstLetter)
              .collect(Collectors.toList()))
            );
        }
    
        private static String capitaliseFirstLetter(String s) {
            return (s.length() > 0)
              ? s.substring(0, 1).toUpperCase() + s.substring(1)
              : s;
        }
    
        private static String decapitaliseFirstLetter(String s) {
            return (s.length() > 0)
              ? s.substring(0, 1).toLowerCase() + s.substring(1)
              : s;
        }
    
    }
    

    A unit test:

        @Test
        void jsonWithMiscCasedPropKeys_shouldConvertKeyToCamelCase() throws Exception {
            String inputJson =
                "{\"kebab-prop\": \"kebab\"," +
                "\"snake_prop\": \"snake\"," +
                "\"PascalProp\": \"pascal\"," +
                "\"camelCasedProp\": \"camel\"}";
            String expectedJson =
              "{\"kebabProp\": \"kebab\"," +
                "\"snakeProp\": \"snake\"," +
                "\"pascalProp\": \"pascal\"," +
                "\"camelCasedProp\": \"camel\"}";
            String actualJson = Json.toJsonWithCamelCasedKeys(inputJson);
    
            JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.LENIENT);
        }
    

提交回复
热议问题