我正在使用spring boot和MySQL开发一个应用程序。我也使用JDBCTemplate
与spring boot应用程序中的数据库进行交互。
在特定情况下,我正在调用一个存储过程,它返回结果集,如下所示: (示例数据)
Cluster AppType Application
-----------------------------------------
C1 AT1 A
C1 AT1 B
C1 AT2 A
C1 AT2 B
我将此结果映射到pojo,如下所示:
存储库:
public List<UserSubHierarchy> getUserHierarchy() {
List<UserSubHierarchy> listCount = new LinkedList<>();
String sql = " call GET_USER_SUBHIERARCHY()";
listCount = jdbcTemplate.query(sql, new BeanPropertyRowMapper<UserSubHierarchy>(UserSubHierarchy.class));
return listCount;
}
POJO的:
public class UserSubHierarchy {
private String apm_buisness_cluster;
private String apm_application_type;
private String apm_application_name;
// setter and getter
}
在此之后我需要处理List<UserSubHierarchy>
并输出如下输出:
[
{
"text":"C1",
"children":[
{
"text":"AT1",
"children":[
{
"text":"A",
"children":null
},
{
"text":"B",
"children":null
}
]
},
{
"text":"AT2",
"children":[
{
"text":"A",
"children":null
},
{
"text":"B",
"children":null
}
]
}
]
}
]
对于上述JSON
格式,我创建了pojo,如下所示:
public class AppList{
private String text;
private List<AppList> children;
//getter and setter
}
我已经尝试了两天,我无法带来我预期的输出。请帮助我或指导我获得解决方案。我想我清楚地提到了我所有的资源,如果不是请让我知道。在此先感谢所有人。
答案 0 :(得分:0)
要将项目收集到地图结构中,您可以执行以下操作:
final Map<String, Map<String, List<UserSubHierarchy>>> out = list.stream().collect(
Collectors.groupingBy(UserSubHierarchy::getApm_buisness_cluster,
Collectors.groupingBy(UserSubHierarchy::getApm_application_type)));
这会返回以下数据:
{C1={
AT1=[
WIMdataReader$UserSubHierarchy@7a79be86,
WIMdataReader$UserSubHierarchy@34ce8af7],
AT2=[
WIMdataReader$UserSubHierarchy@b684286,
WIMdataReader$UserSubHierarchy@880ec60]}}
如果您的数据具有与上述数据类似的固定结构,那么您可以跳过子项标签,只需按原样对地图进行编码,使用您喜欢的任何JSON库,输出如下:
{
"C1":{
"AT1":[
"A",
"B"
],
"AT2":[
"A",
"B"
]
}
}
public class WIMdataReader {
public static class UserSubHierarchy {
private String buisnessCluster;
private String applicationType;
public String getBuisnessCluster() {
return buisnessCluster;
}
public String getApplicationType() {
return applicationType;
}
private String applicationName;
public UserSubHierarchy(String buisnessCluster, String applicationType, String applicationName) {
this.buisnessCluster = buisnessCluster;
this.applicationType = applicationType;
this.applicationName = applicationName;
}
@Override
public String toString() {
return applicationName;
}
}
private static final List<UserSubHierarchy> list = List.of(
new UserSubHierarchy("C1", "AT1", "A"),
new UserSubHierarchy("C1", "AT1", "B"),
new UserSubHierarchy("C1", "AT2", "A"),
new UserSubHierarchy("C1", "AT2", "B")
);
public static void main(final String... args) {
final Map<String, Map<String, List<UserSubHierarchy>>> out =
list.stream().collect(
Collectors.groupingBy(UserSubHierarchy::getBuisnessCluster,
Collectors.groupingBy(UserSubHierarchy::getApplicationType)));
System.out.println(out);
}
}
输出:{C1={AT1=[A, B], AT2=[A, B]}}