Jackson json to map and camelcase key name

后端 未结 2 1840
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 19:27

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

from

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


        
2条回答
  •  日久生厌
    2021-02-14 20:06

    You always can iterate over the keys of the map and update them. However, if you are only interested in producing a JSON with camel case keys, you could consider the approach described below.

    You could have a custom key serializer. It will be used when serializing a Map instance to JSON:

    public class CamelCaseKeySerializer extends JsonSerializer {
    
        @Override
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
                    throws IOException, JsonProcessingException {
    
            String key = Character.toLowerCase(value.charAt(0)) + value.substring(1);
            gen.writeFieldName(key);
        }
    }
    

    Then do as following:

    String json = "{\"SomeKey\":\"SomeValue\",\"AnotherKey\":\"another value\",\"InnerJson\":"
                + "{\"TheKey\":\"TheValue\"}}";
    
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addKeySerializer(String.class, new CamelCaseKeySerializer());
    
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(simpleModule);
    
    Map map = mapper.readValue(json, 
                                              new TypeReference>() {});
    
    String camelCaseJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
    

    The output will be:

    {
      "someKey" : "SomeValue",
      "anotherKey" : "another value",
      "innerJson" : {
        "theKey" : "TheValue"
      }
    }
    

    With this approach, the keys of the Map won't be in camel case. But it will give you the desired output.

提交回复
热议问题