简体   繁体   中英

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!

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, "");
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM