java properties to json

后端 未结 10 1582
情书的邮戳
情书的邮戳 2020-12-13 18:06

Is there an easy way to convert properties with dot notation to json

I.E

server.host=foo.bar
server.port=1234

TO

{
         


        
10条回答
  •  -上瘾入骨i
    2020-12-13 19:01

    I didn't want any dependency on gson and I wanted to return a hierarchical json from a Spring controller so a deep Map was enough for me.

    This works for me, just loop over all your keys and pass in an empty map.

    void recurseCreateMaps(Map currentMap, String key, String value) {
        if (key.contains(".")) {
            String currentKey = key.split("\\.")[0];
    
            Map deeperMap;
    
            if (currentMap.get(currentKey) instanceof Map) {
                deeperMap = (Map) currentMap.get(currentKey);
            } else {
                deeperMap = new HashMap<>();
                currentMap.put(currentKey, deeperMap);
            }
    
            recurseCreateMaps(deeperMap, key.substring(key.indexOf('.') + 1), value);
        } else {
            currentMap.put(key, value);
        }
    }
    

提交回复
热议问题