【发布时间】:2019-04-21 07:50:07
【问题描述】:
我需要关于如何最好地遍历 List<Map<String, String>> 对象以获得以下结果的建议:
该对象包含从 sql 数据库中获取的数据。每个 Map 条目描述了返回数据的单列:
0 =
0 =
key = "ColumnA"
value = "1"
1 =
key = "ColumnB"
value = "2"
2 =
key = "ColumnC"
value = "3"
1 =
0 =
key = "ColumnA"
value = "1"
1 =
key = "ColumnB"
value = "2"
2 =
key = "ColumnC"
value = "3"
一个实际的数据示例如下所示:
0 =
0 =
key = "Itemtype"
value = "1"
1 =
key = "Itemdate"
value = "01.01.2018"
2 =
key = "Subitem"
value = "A"
3 =
key = "Subitemdetail"
value = "A"
4 =
key = "Subitemdetail2"
value = "A"
1 =
0 =
key = "Itemtype"
value = "1"
1 =
key = "Itemdate"
value = "01.01.2018"
2 =
key = "Subitem"
value = "B"
3 =
key = "Subitemdetail"
value = "B"
4 =
key = "Subitemdetail2"
value = "B"
2 =
0 =
key = "Itemtype"
value = "2"
1 =
key = "Itemdate"
value = "01.01.2018"
2 =
key = "Subitem"
value = "A"
3 =
key = "Subitemdetail"
value = "A"
4 =
key = "Subitemdetail2"
value = "A"
3 =
0 =
key = "Itemtype"
value = "2"
1 =
key = "Itemdate"
value = "01.01.2018"
2 =
key = "Subitem"
value = "B"
3 =
key = "Subitemdetail"
value = "B"
4 =
key = "Subitemdetail2"
value = "B"
目前,数据通过 sn-p 以与 JSON 类似的格式返回:
JSONArray resultSet = new JSONArray();
for (Map<String, String> res : data) {
JSONObject resObject = new JSONObject();
for (Entry<String, String> subres : res.entrySet()) {
resObject.put(subres.getKey(), subres.getValue());
}
resultSet.put(resObject);
}
上面的sn-p返回如下JSON:
{
"res":[
{
"Itemtype": "1",
"Itemdate": "01.01.2018",
"Subitem": "A",
"Subitemdetail": "A",
"Subitemdetail2": "A"
},
{
"Itemtype": "1",
"Itemdate": "01.01.2018",
"Subitem": "B",
"Subitemdetail": "B",
"Subitemdetail2": "B"
},
{
"Itemtype": "2",
"Itemdate": "01.01.2018",
"Subitem": "A",
"Subitemdetail": "A",
"Subitemdetail2": "A"
},
{
"Itemtype": "2",
"Itemdate": "01.01.2018",
"Subitem": "B",
"Subitemdetail": "B",
"Subitemdetail2": "B"
}
]}
期望的结果:
但是,我现在想根据 Itemtype 值对 JSON 进行分组。期望的结果如下:
{
"result":[
{
"Itemtype": "1",
"Itemdate": "01.01.2018",
"Subitem": [
{
"Subitem": "A",
"Subitemdetail": "A",
"Subitemdetail2": "A"
},
{
"Subitem": "B",
"Subitemdetail": "B",
"Subitemdetail2": "B"
}
]
},
{
"Itemtype": "2",
"Itemdate": "01.01.2018",
"Subitem": [
{
"Subitem": "A",
"Subitemdetail": "A",
"Subitemdetail2": "A"
},
{
"Subitem": "B",
"Subitemdetail": "B",
"Subitemdetail2": "B"
}
]
}
]}
我正在想办法如何最好地遍历List<Map<String, String>> 对象。你能给我一个建议吗?
因为我目前只能想到非常丑陋的解决方案,例如,首先将对象作为一个整体进行检查,然后存储一个 itemtypes 列表及其位置,对于上面的示例意味着: 第 1 项:0、1 和第 2 项:1、2。 然后,我将浏览列表并为自己构建 JSON。但也许你可以给我一个更好的方法的建议?或者甚至有一个 Java 8 流可以更好地解决这个问题?
提前致谢!
【问题讨论】:
-
你拉错了数据。您从 Web 服务器或从任何地方获取的结果是否采用正确的 JSON 格式?我绝对可以帮助你,我只需要更多信息。发布你从服务器获得的数据结果。
-
如果您打算在某个时候对数据执行一些业务逻辑,最好将数据放在一个类中。否则它会变得一团糟(如您所见)并且您并不是真正使用 Java 编程。
-
我可以在几个小时内发布数据结果。但是,您将如何以不同的方式提取数据?关于将数据放入一个类中:我的想法相同,但目前没有对数据做任何其他事情,所以现在这只是一个额外的步骤,无论如何我仍然需要一种方法来遍历它:)跨度>
标签: java json java-8 iteration