Jackson json to map and camelcase key name

后端 未结 3 1597
没有蜡笔的小新
没有蜡笔的小新 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:16

    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.

提交回复
热议问题