java - 通过拆分字符串创建 JSON?
问题描述
所以我有一种情况,我从数据库中获取一些我无法更改/更新的数据。所以我来自 2 列的数据是这样的:
例如:
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 ...
推荐阅读
- sql - 从任何地方访问 Azure Sql 服务器/VSTS 管道
- firebase - firebase 功能 - `firebase deploy` - 该服务当前不可用
- arrays - Angular 6:如何将 JSON 字符串添加到现有的 JSON 字符串数组?
- java - 为什么我的插入排序比合并排序快?
- c++ - 交叉编译时包含外部库
- android - 如何将聊天值设置为图像视图和文本视图?
- java - Eclipse 看不到 Java
- excel - Excel vlookup 从工作表 A 中查找 3 列并与工作表 B 中的两列匹配,并在工作表 B 中给出第 3 列
- kubernetes - Kubectl 仅获取工作节点
- javascript - React:如果 prop 的一部分不可用,有没有办法避免类型错误?