首页 > 解决方案 > Java:将点分隔的字符串转换为嵌套的 JSON 值

问题描述

我有一堆以点分隔的字符串形式出现的对象属性,例如“company.id”、“company.address.number”、“user.name”、“isAtive”,我需要创建一个与其各自嵌套的 JSON价值观。这些属性和值在 HashMap 中。

并非所有事物都是 3 级深:许多只有 1 级深,许多都比 3 级深。

代码示例:

public static void main(String[] args) {
    Map<String, String[]> list = new HashMap<>();
    list.put("params.isAtive", new String[] {"true"});
    list.put("params.user.name", new String[] {"John Diggle"});
    list.put("params.company.id", new String[] {"1"});
    list.put("params.company.name", new String[] {"SICAL MOTORS"});
    list.put("params.company.address.number", new String[] {"525"});
    list.put("params.company.address.street", new String[] {"Park Avenue"});
    list.put("params.models", new String[] {"55", "65"});
    JSONObject jsonReq = new JSONObject();
    for(Entry<String, String[]> entry : list.entrySet()) {
        String key = entry.getKey().replaceAll("params\\.", "");
        String value = entry.getValue().length == 1 ? entry.getValue()[0] : Arrays.toString(entry.getValue());
        String [] spl = key.split("\\.");
        if(spl.length == 1) {
            jsonReq.put(key, value);
        } else {
            for (int i = 0; i < spl.length; i++) {
                if(i == spl.length - 1) {
                    jsonReq.getJSONObject(spl[i-1]).put(spl[i], value);
                } else {
                    if((i-1) > 0) {
                        if(!jsonReq.getJSONObject(spl[i-1]).has(spl[i])) {
                            jsonReq.getJSONObject(spl[i-1]).put(spl[i], new JSONObject());
                        }
                    } else {
                        if(!jsonReq.has(spl[i])) {
                            jsonReq.put(spl[i], new JSONObject());
                        }
                    }
                }
            }
        }
    }
    System.out.println(jsonReq.toString());
}

当前结果:

{"models":"[55, 65]","address":{"number":"525","street":"Park Avenue"},"company":{"name":"SICAL MOTORS","id":"1"},"user":{"name":"John Diggle"},"isAtive":"true"}

预期结果:

{"models":"[55, 65]","company":{"name":"SICAL MOTORS","id":"1","address":{"number":"525","street":"Park Avenue"}},"user":{"name":"John Diggle"},"isAtive":"true"}

示例中不需要使用 JSONObject,我只需要一些东西来解决这个问题。

标签: javajsonserializationhashmap

解决方案


推荐阅读