首页 > 解决方案 > 将从 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

标签: javajsonalgorithmnested

解决方案


正如评论中所建议的,让我们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
}]

推荐阅读