public class User {
public String email;
public String fullname;
public User(String email, String fullname) {
this.email = email;
this.fullname = fullname;
}
}
import com.google.gson.Gson;
public class ToJsonSample {
/*
* JavaオブジェクトからJSONへの変換
*/
public static void main(String[] args) {
User user = new User("jeff@jmail.com", "Jeff");
{
Post newPost = new Post() {
{
setUser(user);
this.title = null;
this.content = null;
}
};
Comment comment = new Comment("comment_author", "comment_comment");
newPost.comments.add(comment);
newPost.comments.add(comment);
System.out.println("Gson Post" + new Gson().toJson(newPost)); // null
System.out.println(" This Post class is : " + newPost.getClass()); // Postではなく一時クラス
System.out.println(" Gson Post: " + new Gson().toJson(newPost, Post.class)); // なお,Typeを指定すると正しく表示できる
// {"author":{"email":"jeff@jmail.com","fullname":"Jeff"},"comments":[{"author":"comment_author","content":"comment_comment"},{"author":"comment_author","content":"comment_comment"}]}
}
{
Post newPost = new Post();
newPost.author = mUsers.get(0);
Comment comment = new Comment("comment_author", "comment_comment");
newPost.comments.add(comment);
newPost.comments.add(comment);
System.out.println("Gson Post: " + new Gson().toJson(newPost));
// {"author":{"email":"jeff@jmail.com","fullname":"Jeff"},"comments":[{"author":"comment_author","content":"comment_comment"},{"author":"comment_author","content":"comment_comment"}]}
System.out.println(" This Post class is : " + newPost.getClass()); // Post
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Post {
public String title;
public String content;
public User author;
public List<Comment> comments;
public Post() {
this.comments = new ArrayList<Comment>();
}
public Post(User author, String title, String content) {
this.comments = new ArrayList<Comment>();
this.author = author;
this.title = title;
this.content = content;
}
public void setUser(User user) {
this.author = user;
}
}
public class Comment {
public String author;
public String content;
public Comment(String author, String content) {
this.author = author;
this.content = content;
}
}