Java:将点分隔的字符串转换为嵌套的JSON值

时间:2018-07-12 16:59:52

标签: java json serialization hashmap

我有一堆对象属性以点分隔的字符串形式出现,例如“ 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,我只需要一些东西来解决这个问题。

0 个答案:

没有答案