所以我遇到一种情况,我从数据库中获取一些无法更改/更新的数据。所以我的两列数据如下:
例如:
Column1 Column2
Row 1: hello.how.are.you Gracie
Row 2: hello.how.is.she John
Row 3: hello.how.is.he Gurinder
Row 4: hello.from.me Singh
所以我需要创建一个如下所示的 JSON:
{
"hello":{
"how":{
"are":{
"you":"Gracie"
},
"is":{
"he":"Gurinder",
"she":"John"
}
},
"from":{
"me":"Singh"
}
}
}
我想要一些优化方法来创建我的 JSON。谢谢!
public static void main(String[] args) {
List<String > stringList = new ArrayList();
stringList.add("hello.how.are.you");
stringList.add("hello.how.is.she");
stringList.add("hello.how.is.he");
stringList.add("hello.from.me");
JSONObject response = new JSONObject();
for (String str : stringList) {
String[] keys = str.split("\\.");
for (int i = 0; i < keys.length; i++) {
if (response.has(keys[i])) {
} else {
JSONObject jsonObject2 = new JSONObject()
response.append(keys[i], jsonObject2);
}
}
}
}
我正在做类似的事情并试图解决。
最佳答案
您用于输入的内容需要保存所有数据(包括第 2 列)。假设input
变量是 HashMap<String, String>
等于
{
"hello.how.are.you" : "Gracie",
...
}
目前,您的代码看起来已经步入正轨。问题是,您要附加到 response
,当您想要附加到 JSON 树深处的某个值时。
JSONObject parent = response;
for(...) {
// If there's no JSON there, just make it
if( !parent.has(keys[i]) ) {
// It's not already in there, so let's make it
parent.put(keys[i], new JSONObject()); // response["hello"] = {}
}
// Now, look at how this works. If keys = ["hello", "how", "are", "you"],
// Then when i == 0, parent <= response["hello"]
// That way you do response["hello"].append("how", {}) on the next iteration
parent = (JSONObject)parent.get(keys[i]);
}
您还需要处理尾部情况,您可以使用类似的东西来完成
if( i == keys.length - 1 ) {
parent.put(keys[i], input.get(str)); // str = "hello.how.are.you"
// input.get("hello.how.are.you") == "Gracie"
} else ...
关于java - 通过分割字符串创建 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51676823/