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.