java - 将从 DB 读取创建的平面 Java 对象转换为嵌套的 Json 对象
问题描述
commenId
线程化的评论作为带有和的平面记录存储在数据库中ParentCommentId
。如下所示。
commentId : 1
userId : 815
userFName:Joe
userLName:Doe
timeStamp:12345678888
commentText:""
parentCommentId:0
commentId : 2
userId : 615
userFirstName:Ken
userLastName:Tait
timeStamp:12345678988
commentText:"Comment text"
parentCommentId:1
commentId : 3
userId : 415
userFirstName:Brain
userLastName:Dell
timeStamp:12345678
commentText:"Comment text"
parentCommentId:0
我使用以下 Java 类构建 Java 对象
public class Comment {
int commentId;
int userId;
String userFName;
String userLName;
long timeStamp;
String commentText;
int parCommId;
}
List<Comment> comments;
我有List
评论对象。现在我必须遍历列表并将这个评论对象列表转换为嵌套的 Json 对象。注释对象parCommId == 0
是顶级注释,其他注释对象 ( parCommId != 0
) 应嵌套在commentId
注释对象的 下方。
在上面的例子中,输出应该嵌套如下
CommentId_1
CommentId_2
CommentID_3
解决方案
正如评论中所建议的,让我们List<Comment>
在Comment.class
.
然后,假设来自数据库的输入是:
List<Comment> comments = Arrays.asList(
new Comment(1, 6, "John", "Snow", 0, "asd", 0),
new Comment(2, 6, "Tif", "Snow", 0, "asd2", 1),
new Comment(3, 6, "Yur", "Snow", 0, "asd", 2),
new Comment(4, 6, "Mrr", "Snow", 0, "asd", 0),
new Comment(5, 6, "Mrr", "Snow", 0, "asd", 2)
);
您可以执行以下操作:
Map<Integer, List<Comment>> parentToComments = comments.stream()
.collect(Collectors.groupingBy(Comment::getParCommId));
comments.forEach(comment -> {
List<Comment> children = parentToComments.get(comment.getCommentId());
comment.setChildren(children);
});
ObjectMapper objectMapper = new ObjectMapper();
String commentsJson = objectMapper.writeValueAsString(parentToComments.get(0));
输出:
[{
"commentId": 1,
"userId": 6,
"userFName": "John",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 0,
"children": [{
"commentId": 2,
"userId": 6,
"userFName": "Tif",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd2",
"parCommId": 1,
"children": [{
"commentId": 3,
"userId": 6,
"userFName": "Yur",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 2,
"children": null
}, {
"commentId": 5,
"userId": 6,
"userFName": "Mrr",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 2,
"children": null
}]
}]
}, {
"commentId": 4,
"userId": 6,
"userFName": "Mrr",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 0,
"children": null
}]
推荐阅读
- java - 我已经为数组编写了代码,但 logcat 没有显示错误
- android - 在 JobIntentService 中可以在没有 onHandleWork() 的情况下调用 onDestroy() 吗?
- jenkins - 无法在 Jenkins 中使用多级目录/文件存储目录
- c# - 在 wpf/mvvm 应用程序中嵌入 qt/C++ 应用程序的主窗口
- angular - 为什么 ReplaySubject 返回所有值?
- merge - 从命名阶段将数据合并到表中
- ansible - 如何在 AWX 上限制模板中的主机?
- macos - 如何在 macOS 上使用 iterm 作为默认终端?
- c# - SSIS Web API 连接
- javascript - 滚动容器高度设置为小于窗口高度