1

我需要使用嵌套字段从属性文件创建 JSON?例如,我们有以下属性文件:

student.name="John"
student.exam.math=5
teacher.skills=10

我需要输出以下 JSON 文件:

Properties : {
    student : {
        name : "John",
        exam : {
            math : 5
        }
    },
    teacher : {
       skills : 10
    }
}

JSON 代码可以使用 FLEX-JSON 序列化器或 GSON 库生成,这不是问题。主要问题是解析属性并生成具有嵌套属性的 Java Object 或 Map。有没有图书馆允许这样做?谢谢!

4

2 回答 2

5

AFAIK,没有知名的图书馆可以做到这一点。但是你可以用一种简单的方式做到这一点:

 public String propertiesToJson(Properties p) {
    Map tree = new LinkedHashMap();

    for (String name : p.stringPropertyNames()) {
        String[] parts = name.split("\\.");
        Map nextTree = tree;
        for (int i = 0, partsLength = parts.length; i < partsLength; i++) {
            String part = parts[i];
            Object v = nextTree.get(part);
            if (v == null) {
                if (i < partsLength - 1) {
                    Map newNextTree = new LinkedHashMap();
                    nextTree.put(part, newNextTree);
                    nextTree = newNextTree;
                } else {
                    nextTree.put(part, p.getProperty(name));
                }
            } else {
                if (i < partsLength - 1) {
                    nextTree = (Map) v;
                }
            }
        }
    }


    StringBuilder sb = new StringBuilder();
    sb.append("Properties : {\n");
    recursive(tree, sb, 1);
    sb.append("}");

    return sb.toString();
}

private void recursive(Map tree, StringBuilder sb, int deep) {
    boolean first = true;
    for (Object key : tree.keySet()) {
        if (!first) sb.append(",\n");
        else first = false;
        for (int t = 0; t < deep; t++) sb.append("\t");
        sb.append(key + " : ");
        Object v = tree.get(key);
        if (v instanceof Map) {
            sb.append("{\n");
            recursive((Map) v, sb, deep+1);
            for (int t = 0; t < deep; t++) sb.append("\t");
            sb.append("}");
        } else {
            sb.append(v);
        }
    }
    sb.append("\n");
}
于 2012-12-17T11:11:15.713 回答
1

即使这篇文章较旧,一个非常简单的解决方案是使用Jackson JavaPropsMapper

flatMessages = ...;
JavaPropsMapper mapper = new JavaPropsMapper();
Map ret = mapper.readPropertiesAs(flatMessages, HashMap.class);
于 2018-07-17T10:44:44.113 回答