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'
}
使用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"
}