java properties to json

后端 未结 10 1604
情书的邮戳
情书的邮戳 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 18:49

    A little bit recursion and Gson :)

    public void run() throws IOException {
    
        Properties properties = ...;
    
        Map map = new TreeMap<>();
    
        for (Object key : properties.keySet()) {
            List keyList = Arrays.asList(((String) key).split("\\."));
            Map valueMap = createTree(keyList, map);
            String value = properties.getProperty((String) key);
            value = StringEscapeUtils.unescapeHtml(value);
            valueMap.put(keyList.get(keyList.size() - 1), value);
        }
    
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(map);
    
        System.out.println("Ready, converts " + properties.size() + " entries.");
    }
    
    @SuppressWarnings("unchecked")
    private Map createTree(List keys, Map map) {
        Map valueMap = (Map) map.get(keys.get(0));
        if (valueMap == null) {
            valueMap = new HashMap();
        }
        map.put(keys.get(0), valueMap);
        Map out = valueMap;
        if (keys.size() > 2) {
            out = createTree(keys.subList(1, keys.size()), valueMap);
        }
        return out;
    }
    

提交回复
热议问题