Gson入門 | Quick tutorial to Gson

Gson是Google的開源的處理Json的library。個人覺得比Jackson好用。

gson添加到build.gradle的dependency里,gradle入門請參考之前博文」怎樣用gradle建立一個新的Java項目 | how to create a new Java project using gradle「。

dependencies {
    implementation 'com.google.code.gson:gson:2.8.6'
}
點擊Intelij Idea Gradle Plugin左上角的「刷新」
刷新後,在左邊項目結構的External Libraries里看到gson,就是添加成功了

使用Gson例子

Gson gson = new Gson();
String json = gson.toJson(someObject)

這裡json是緊湊型的

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(someObject);

這裡的json是pretty print的

例子


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonDemo {
    public String name;
    public String url;
    public String description;

    @Override
    public String toString() {
        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();
        return gson.toJson(this);
    }

    public static void main(String[] args) {
        GsonDemo gsonDemo = new GsonDemo();
        gsonDemo.name = "Feellikelearning";
        gsonDemo.url = "feellikelearning.com";
        gsonDemo.description = "feellikelearning.com - The blog about learning technology";

        System.out.println(gsonDemo);
    }
}

運行結果

{
  "name": "Feellikelearning",
  "url": "feellikelearning.com",
  "description": "feellikelearning.com - The blog about learning technology"
}

Leave a Comment

Your email address will not be published.