Jackson json to map and camelcase key name

后端 未结 2 1851
被撕碎了的回忆
被撕碎了的回忆 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<String> {
    
        @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<String, Object> map = mapper.readValue(json, 
                                              new TypeReference<Map<String, Object>>() {});
    
    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.

    0 讨论(0)
  • 2021-02-14 20:09

    As you are working with maps/dictionaries instead of binding the JSON data to POJOs (explicit Java classes that match the JSON data), the property naming strategy does not apply:

    Class PropertyNamingStrategy ... defines how names of JSON properties ("external names") are derived from names of POJO methods and fields ("internal names")

    Therefore, you have to first parse the data using Jackson and then iterate over the result and convert the keys.

    Change your code like this:

    public Map<String, Object> jsonToMap(String jsonString) throws IOException
    {
        ObjectMapper mapper=new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        Map<String, Object> map = mapper.readValue(jsonString,new TypeReference<Map<String, Object>>(){});
        return convertMap(map);
    }
    

    And add these methods:

    public String mapKey(String key) {
        return Character.toLowerCase(key.charAt(0)) + key.substring(1);
    }
    
    public Map<String, Object> convertMap(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            result.put(mapKey(key), convertValue(value));
        }
        return result;
    }
    
    public convertList(Lst<Object> list) {
        List<Object> result = new ArrayList<Object>();
        for (Object obj : list) {
            result.add(convertValue(obj));
        }
        return result;
    }
    
    public Object covertValue(Object obj) {
        if (obj instanceof Map<String, Object>) {
            return convertMap((Map<String, Object>) obj);
        } else if (obj instanceof List<Object>) {
            return convertList((List<Object>) obj);
        } else {
            return obj;
        }
    }
    
    0 讨论(0)
提交回复
热议问题