LoginSignup
306
313

More than 5 years have passed since last update.

GSONの基本的な使い方

Posted at

はじめに

GSONは、Googleが提供するJSONデータとJavaオブジェクトを相互に変換するためのライブラリです。
google-gson - A Java library to convert JSON to Java objects and vice-versa - Google Project Hosting
https://code.google.com/p/google-gson/

JavaでJSONを扱うためのライブラリは他にJacksonJSONIC等があります。

GSONのメインとなるのは Gson クラスです。
GsonBuilder クラスを使うとより詳細な条件を指定してJavaとJSONの変換を行うことができます。
ここではGsonクラスの使い方を紹介します。

サンプルで使用するクラス

シンプルなJavaのクラスです。
PostはフィールドにUserオブジェクトとCommentオブジェクトのListを持っています。

User.java
public class User {
    public String email;
    public String fullname;

    public User(String email, String fullname) {
        this.email = email;
        this.fullname = fullname;
    }
}
Post.java
public class Post {
    public String title;
    public String content;
    public User author;
    public List<Comment> comments;

    public Post(User author, String title, String content) {
        this.comments = new ArrayList<Comment>();
        this.author = author;
        this.title = title;
        this.content = content;
    }
}
Comment.java
public class Comment {
    public String author;
    public String content;

    public Comment(String author, String content) {
        this.author = author;
        this.content = content;
    }
}

シリアライズ - toJson()

JavaからJSONへ変換する時は toJson() を使います。
デフォルトではnullのフィールドはJSONに含まれません。

ToJsonSample.java
public class ToJsonSample {
    /*
     *  JavaオブジェクトからJSONへの変換
     */
    public static void main(String[] args) {
        Gson gson = new Gson();

        User user1 = new User("bob@jmail.com", null);       //fullnameにnullをセット
        User user2 = new User("jeff@jmail.com", "Jeff");
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);

        // JavaオブジェクトからJSONへの変換
        System.out.println("ユーザー: " + gson.toJson(user1));

        // JavaオブジェクトからJSONへの変換:List
        System.out.println("ユーザーリスト: " + gson.toJson(userList));

        Post newPost = new Post(userList.get(0), "postTitle", "postContent");
        Comment comment = new Comment("comment_author", "comment_comment");
        newPost.comments.add(comment);
        newPost.comments.add(comment);

        // JavaオブジェクトからJSONへの変換:フィールドにListを含むオブジェクト
        System.out.println("コメント付き投稿: " + gson.toJson(newPost));
    }
}

実行結果

ユーザー: {"email":"bob@jmail.com"}
ユーザーリスト: 
[
    {
        "email": "bob@jmail.com",
        "fullname": "Bob"
    },
    {
        "email": "jeff@jmail.com",
        "fullname": "Jeff"
    }
]
コメント付き投稿: 
{
    "title": "postTitle",
    "content": "postContent",
    "author": {
        "email": "bob@jmail.com",
        "fullname": "Bob"
    },
    "comments": [
        {
            "author": "comment_author",
            "content": "comment_comment"
        },
        {
            "author": "comment_author",
            "content": "comment_comment"
        }
    ]
}

デシリアライズ - fromJson()

JSONからJavaへ変換する時は fromJson() を使います。

FromJsonSample.java
public class FromJsonSample {

    /*
     *  JSONからJavaオブジェクトへの変換
     */
    public static void main(String[] args) {
        Gson gson = new Gson();

        // JSONからStringへの変換
        String str = gson.fromJson("\"hello\"", String.class);
        System.out.println("String: " + str);

        // JSONからJavaオブジェクトへの変換 
        User user = gson.fromJson("{\"email\":\"bob@jmail.com\",\"fullname\":\"Bob\"}", User.class);
        System.out.println("User: " + user.email + " / " + user.fullname);

        // JSONから配列への変換
        int[] array = gson.fromJson("[1, 2, 3]", int[].class);
        System.out.println("int[]: " + array[0] + ", " + array[1] + ", " + array[2]);

        // JSONからListへの変換
        List list = gson.fromJson("[\"hello\", \"hellohello\",\"hellohellohello\"]", List.class);
        System.out.println("List: " + list.get(0) + ", " + list.get(1) + ", " + list.get(2));

        // JSONからフィールドにListを含むJavaオブジェクトへの変換 
        String jsonStr = "{\"title\":\"投稿タイトル\",\"content\":\"本文本文本文\","
                + "\"author\":{\"email\":\"bob@jmail.com\",\"fullname\":\"Bob\"},"
                + "\"comments\":[{\"author\":\"Tom\",\"content\":\"コメント本文\"}]"
                + "}";
        Post post = gson.fromJson(jsonStr, Post.class);
        System.out.println("Post: タイトル=" + post.title 
                            + ", 著者=" + post.author.fullname 
                            + ", コメント件数=" + post.comments.size());      
    }
}

実行結果

String: hello
User: bob@jmail.com / Bob
int[]: 1, 2, 3
List: hello, hellohello, hellohellohello
Post: タイトル=投稿タイトル, 著者=Bob, コメント件数=1
306
313
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
306
313