3

I'm looking for good way or complete API to create a hierarchical JSON from plain java.util.Properties object.

Exist java.util.Properties object, e.g.:

car.color=blue
car.places=4
car.motor.dimension=2L
car.motor.ps=120

and the target json structur should be:

{
 "car":
  {"color":"blue",
   "places":4,
   "motor":
    {"dimension":"2L",
     "ps":120
    }
  }
}

3 Answers 3

3
public void run() throws IOException {

    Properties properties = ...;

    Map<String, Object> map = new TreeMap<>();

    for (Object key : properties.keySet()) {
        List<String> keyList = Arrays.asList(((String) key).split("\\."));
        Map<String, Object> valueMap = createTree(keyList, map);
        String value = properties.getProperty((String) key);
        value = StringEscapeUtils.unescapeHtml(value);
        valueMap.put(keyList.get(keyList.size() - 1), value);
    }

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(map);

    System.out.println("Ready, converts " + properties.size() + " entries.");
}

@SuppressWarnings("unchecked")
private Map<String, Object> createTree(List<String> keys, Map<String, Object> map) {
    Map<String, Object> valueMap = (Map<String, Object>) map.get(keys.get(0));
    if (valueMap == null) {
        valueMap = new HashMap<String, Object>();
    }
    map.put(keys.get(0), valueMap);
    Map<String, Object> out = valueMap;
    if (keys.size() > 2) {
        out = createTree(keys.subList(1, keys.size()), valueMap);
    }
    return out;
}
Sign up to request clarification or add additional context in comments.

Comments

2

The following project 'Java Properties to JSON' achieves exactly what you seek.

However, it has a restriction on Java 8.

Would be great if someone actually provides changes to make it Java 7 compatible.

1 Comment

For now that project support Java 7.
1

You will need to parse your properties to Map<String, Object> where your Object will be either another Map<String, Object> or a String. For this you will have to write your own code. I suppose you will need to take your properties keys and split them over "." using method String.split(). Note that in your code you will need to use "\\." as a parameter as "." is a regular expression. Once you build your Map it is very easy to convert it to JSON using Jackson library or any available JSON library.

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.