You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数据库读取的扁平层级评论Java对象列表转换为嵌套JSON结构

Convert Flat Comment List to Nested JSON in Java

Alright, let's break this down step by step. You have a flat list of Comment objects stored with commentId and parCommId, and need to turn them into a nested JSON structure where top-level comments (those with parCommId == 0) hold their child comments. Here's how to do it properly:

1. Update the Comment Class

First, we need to add a field to store child comments—your existing class doesn't have a way to hold nested comments. We'll add a List<Comment> and include getters/setters for all fields (required for JSON serialization):

public class Comment {
    int commentId;
    int userId;
    String userFName;
    String userLName;
    long timeStamp;
    String commentText;
    int parCommId;
    // Field to hold child comments
    private List<Comment> children = new ArrayList<>();

    // Getters and Setters
    public int getCommentId() { return commentId; }
    public void setCommentId(int commentId) { this.commentId = commentId; }
    public int getUserId() { return userId; }
    public void setUserId(int userId) { this.userId = userId; }
    public String getUserFName() { return userFName; }
    public void setUserFName(String userFName) { this.userFName = userFName; }
    public String getUserLName() { return userLName; }
    public void setUserLName(String userLName) { this.userLName = userLName; }
    public long getTimeStamp() { return timeStamp; }
    public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; }
    public String getCommentText() { return commentText; }
    public void setCommentText(String commentText) { this.commentText = commentText; }
    public int getParCommId() { return parCommId; }
    public void setParCommId(int parCommId) { this.parCommId = parCommId; }
    public List<Comment> getChildren() { return children; }
    public void setChildren(List<Comment> children) { this.children = children; }
}

2. Convert Flat List to Nested Structure

We'll use a Map to quickly look up parent comments by their commentId, then attach each child comment to its parent. Finally, we'll collect all top-level comments:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommentTreeBuilder {
    public static List<Comment> buildNestedCommentTree(List<Comment> flatComments) {
        // Map to store comments by their ID for O(1) lookup
        Map<Integer, Comment> commentLookupMap = new HashMap<>();
        for (Comment comment : flatComments) {
            commentLookupMap.put(comment.getCommentId(), comment);
        }

        List<Comment> topLevelComments = new ArrayList<>();
        for (Comment comment : flatComments) {
            int parentId = comment.getParCommId();
            if (parentId == 0) {
                // Add top-level comments directly to the result list
                topLevelComments.add(comment);
            } else {
                // Find the parent comment and add current comment as its child
                Comment parentComment = commentLookupMap.get(parentId);
                if (parentComment != null) {
                    parentComment.getChildren().add(comment);
                } else {
                    // Optional: Handle cases where parent ID doesn't exist (log warning, etc.)
                    System.out.println("Warning: Parent comment with ID " + parentId + " not found for comment " + comment.getCommentId());
                }
            }
        }

        return topLevelComments;
    }
}

3. Serialize to Nested JSON

We'll use Jackson (a popular JSON library) to convert the nested comment list into JSON. First, add the Jackson dependency to your project (if using Maven):

<!-- Maven dependency for Jackson -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest stable version -->
</dependency>

Then, serialize the nested list to JSON:

import com.fasterxml.jackson.databind.ObjectMapper;

public class CommentJsonConverter {
    public static void main(String[] args) throws Exception {
        // Replace this with your actual flat Comment list
        List<Comment> flatComments = getSampleFlatComments();

        // Build the nested comment tree
        List<Comment> nestedComments = CommentTreeBuilder.buildNestedCommentTree(flatComments);

        // Convert to pretty-printed JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String nestedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(nestedComments);

        // Output the result
        System.out.println(nestedJson);
    }

    // Dummy method to generate sample flat comments (matches your example)
    private static List<Comment> getSampleFlatComments() {
        List<Comment> comments = new ArrayList<>();

        Comment comment1 = new Comment();
        comment1.setCommentId(1);
        comment1.setUserId(815);
        comment1.setUserFName("Joe");
        comment1.setUserLName("Doe");
        comment1.setTimeStamp(12345678888L);
        comment1.setCommentText("");
        comment1.setParCommId(0);
        comments.add(comment1);

        Comment comment2 = new Comment();
        comment2.setCommentId(2);
        comment2.setUserId(615);
        comment2.setUserFName("Ken");
        comment2.setUserLName("Tait");
        comment2.setTimeStamp(12345678988L);
        comment2.setCommentText("Comment text");
        comment2.setParCommId(1);
        comments.add(comment2);

        Comment comment3 = new Comment();
        comment3.setCommentId(3);
        comment3.setUserId(415);
        comment3.setUserFName("Brain");
        comment3.setUserLName("Dell");
        comment3.setTimeStamp(12345678L);
        comment3.setCommentText("Comment text");
        comment3.setParCommId(0);
        comments.add(comment3);

        return comments;
    }
}

4. Sample Output JSON

Running the code above will produce this nested JSON structure (matching your expected output):

[
  {
    "commentId" : 1,
    "userId" : 815,
    "userFName" : "Joe",
    "userLName" : "Doe",
    "timeStamp" : 12345678888,
    "commentText" : "",
    "parCommId" : 0,
    "children" : [ {
      "commentId" : 2,
      "userId" : 615,
      "userFName" : "Ken",
      "userLName" : "Tait",
      "timeStamp" : 12345678988,
      "commentText" : "Comment text",
      "parCommId" : 1,
      "children" : [ ]
    } ]
  },
  {
    "commentId" : 3,
    "userId" : 415,
    "userFName" : "Brain",
    "userLName" : "Dell",
    "timeStamp" : 12345678,
    "commentText" : "Comment text",
    "parCommId" : 0,
    "children" : [ ]
  }
]

Notes

  • If you prefer using Gson instead of Jackson, the process is similar—just replace the Jackson code with a Gson instance to serialize the nested list.
  • Make sure to handle edge cases, like comments with invalid parent IDs (the code above includes a warning for this).

内容的提问来源于stack exchange,提问作者Shawshank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:18:14