Jackson json to map and camelcase key name

后端 未结 2 1838
被撕碎了的回忆
被撕碎了的回忆 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: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 jsonToMap(String jsonString) throws IOException
    {
        ObjectMapper mapper=new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        Map map = mapper.readValue(jsonString,new TypeReference>(){});
        return convertMap(map);
    }
    

    And add these methods:

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

    提交回复
    热议问题