我可以通过在子类中包含父类来以递归方式反序列化 json?



我有一个类似 json 的东西

{
"author":"jack",
"comment_body":"any message body",
"replies":{
"author":"john",
"comment_body":" reply body",
"replies": {
"author":"john",
"comment_body":" reply body",
"replies":{
...
}
}
}
}

到目前为止,我如何解析这个 json,我的类是

class Comment {
private String author;
private String comment_body;
private Replies replies;
}
class Replies{
private Comment comment_tree;
}

关于如何在gson中解析评论响应的任何帮助?

您不需要回复类。它与您的 JSON 不匹配。这里有一个递归类。

首先,您需要稍微编辑一下 JSON,例如(null添加(:

{
"author": "Jack",
"comment_body": "Any message body",
"replies": {
"author": "John",
"comment_body": "Reply body",
"replies": {
"author": "Smith",
"comment_body": "Another reply body",
"replies": null
}
}
}

接下来,在你的类中创建一个递归变量:

public class Comment {
String author;
String comment_body;
Comment replies;
@Override
public String toString() {
return "Comment{author='" + author + "', comment_body='" + comment_body + "', replies=" + replies + '}';
}
}

最后,可运行的类:

import com.google.gson.Gson;
public class Main {
public static void main (String[] args) {
String json =   "{n" +
"    "author": "Jack",n" +
"    "comment_body": "Any message body",n" +
"    "replies": {n" +
"        "author": "John",n" +
"        "comment_body": "Reply body",n" +
"        "replies": {n" +
"            "author": "Smith",n" +
"            "comment_body": "Another reply body",n" +
"            "replies": nulln" +
"        }n" +
"    }n" +
"}n";
Comment comment = new Gson().fromJson(json, Comment.class);
System.out.println(comment);
}
}

输出:

Comment{author='Jack', comment_body='Any message body', replies=Comment{author='John', comment_body='Reply body', replies=Comment{author='Smith', comment_body='Another reply body', replies=null}}}

你需要反思才能做到这一点......但是你真的应该考虑使用现有的库,比如Jackson,它有ObjectMapper为你完成这项工作。

下面是使用 Jackson 在 JSON 之间序列化/反序列化对象的基础知识的链接。

https://www.baeldung.com/jackson-object-mapper-tutorial

希望对您有所帮助!

你只需要评论类。 试试这个:

class Comment {
private String author;
private String comment_body;
private Comment replies;
}

示例代码:

public class Main {
public static void main(String[] args) {
Comment comment = new Comment();
comment.setAuthor("Outer Author");
comment.setReplies(new Comment());
comment.getReplies().setAuthor("Inner Author");
System.out.println("Author 1 :"+comment.getAuthor());
System.out.println("...Author 2 :"+comment.getReplies().getAuthor());
}
}
class Comment {
private String author;
private String comment_body;
private Comment replies;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getComment_body() {
return comment_body;
}
public void setComment_body(String comment_body) {
this.comment_body = comment_body;
}
public Comment getReplies() {
return replies;
}
public void setReplies(Comment replies) {
this.replies = replies;
}
}

示例输出:

作者1 :外部作者
...作者2:内在作者

最新更新