将从DB read创建的平面Java对象转换为嵌套的Json对象
线程注释作为平面记录存储在数据库中,并带有将从DB read创建的平面Java对象转换为嵌套的Json对象,java,json,algorithm,nested,Java,Json,Algorithm,Nested,线程注释作为平面记录存储在数据库中,并带有commonid和ParentCommentId。如下图所示 commentId : 1 userId : 815 userFName:Joe userLName:Doe timeStamp:12345678888 commentText:"" parentCommentId:0 commentId : 2 userId : 615 user
commonid
和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对象
公共类注释{
int-commentId;
int用户标识;
字符串userFName;
字符串userLName;
长时间戳;
字符串注释文本;
int-parCommId;
}
列出评论;
我有注释对象的列表。现在,我必须遍历列表并将注释对象列表转换为嵌套的Json对象。parCommId==0
的注释对象是顶级注释,其他注释对象(parCommId!=0
)应嵌套在注释对象的commentId
下
在上面的示例中,输出应该像下面那样嵌套
CommentId_1
CommentId_2
CommentID_3
按照注释中的建议,让我们在Comment.class
中添加一个List
字段
然后,假设DB的输入为:
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)
);
您使用的是哪个JSON库?我使用的是JSON simple。com.googlecode.json-simpleStore注释位于Map
中,以commentId
为键。在注释中添加一个字段:列出子项
。然后循环浏览注释映射条目并将子项添加到其父项中-Comment c;map.get(c.parentId).children.add(c)谢谢Janez。这是一个很好的建议,我会尝试一下。非常感谢,这很有魅力。@Shawshank真棒,我很高兴它有帮助;)
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
}]