You don't need Replies class. It doesn't match your JSON. You have one recursive class here.
First of all, you need to edit your JSON a little, for example (added 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
}
}
}
Next, make a recursive variable in your class:
public class Comment {
String author;
String comment_body;
Comment replies;
@Override
public String toString() {
return "Comment{author='" + author + "', comment_body='" + comment_body + "', replies=" + replies + '}';
}
}
Finally, the runnable class:
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\": null\n" +
" }\n" +
" }\n" +
"}\n";
Comment comment = new Gson().fromJson(json, Comment.class);
System.out.println(comment);
}
}
Output:
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}}}