使用Java中属性文件中的嵌套字段创建映射或对象

时间:2012-12-17 10:52:05

标签: java json properties

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

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

我需要输出以下JSON文件:

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

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

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:1)

即使这篇文章比较老,也很简单的解决方法是使用Jackson JavaPropsMapper

flatMessages = ...;
JavaPropsMapper mapper = new JavaPropsMapper();
Map ret = mapper.readPropertiesAs(flatMessages, HashMap.class);