[英]Get JSON tree based on the JSON paths list Java
我的輸入是這樣的:
List.of("customer.name", "customer.phone", "shop.address", "nr")
我必須得到 JSON 樹層次結構,如:
{
customer: {
name: "",
phone: "",
},
shop: {
address: ""
},
nr: ""
}
我正在使用 Java 和 'org.json'、'com.jayway.jsonpath' JSON 依賴項。
請問你有什么想法嗎? 謝謝!
你可以這樣做:
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, "");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.