1

I need to create JSON from Properties file with nested fields? For example, we have the following properties file:

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

And I need the following JSON file on output:

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

JSON code can be produced with FLEX-JSON Serializer or GSON libraries and this is not a problem. The main problem is to parse properties and produce Java Object or Map with nested properties. Is there any library allowing to do that? Thanks!

2 Answers 2

5

AFAIK, there are no well-known libraries for doing that. But you can do this in a trivial way:

 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");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Even as this post is older, a quite easy solution is the usage of the Jackson JavaPropsMapper:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.