Mark
Mark

Reputation: 18827

How to create hierarchical JSON from java.util.Properties object

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
    }
  }
}

Upvotes: 3

Views: 3109

Answers (3)

abdelrahman-sinno
abdelrahman-sinno

Reputation: 1167

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.

Upvotes: 2

Michael Gantman
Michael Gantman

Reputation: 7788

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.

Upvotes: 1

Mark
Mark

Reputation: 18827

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;
}

Upvotes: 3

Related Questions