Search code examples
javajsonjsonpathjson-path-expression

Get JSON tree based on the JSON paths list Java


My input is something like:

List.of("customer.name", "customer.phone", "shop.address", "nr")

And I have to get the JSON tree hierarchy like:

{ 
  customer: {
    name: "",
    phone: "",
  },
  shop: {
    address: ""
  },
  nr: ""
}

I am using Java and 'org.json', 'com.jayway.jsonpath' JSON dependencies.

Do you have any ideas, please? Thank you!


Solution

  • you could do something like this:

    import org.json.JSONObject;
    
    List<String> input = List.of("customer.name", "customer.phone", "shop.address", "nr");
    
    JSONObject root = new JSONObject();
    
    for (String s : input) {
      // Split the string by the '.' character to get the keys
      String[] keys = s.split("\\.");
    
      JSONObject obj = root;
      for (int i = 0; i < keys.length; i++) {
        String key = keys[i];
        if (i < keys.length - 1) {
          if (!obj.has(key)) {
            obj.put(key, new JSONObject());
          }
          obj = obj.getJSONObject(key);
        } else {
          obj.put(key, "");
        }
      }
    }