必須先下載jar檔
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
- 解析Json
import com.google.gson.Gson;
class GsonTest{
private String name;
private int age;
public GsonTest(String string, int i) {
this.name=string;
this.age=i;
}
public static void main(String [] arge) {
Gson gson = new Gson();
//這是一段json
String jsonString = "{\"name\":\"早安\",\"age\":23}";
//將json轉換, 轉換的類型依照test.class的變數
test gson_test = gson.fromJson(jsonString, GsonTest.class);
System.out.println("name="+gson_test.name);
System.out.println("age="+gson_test.age);
}
}
- 生成Json
import com.google.gson.Gson;
class GsonTest{
private String name;
private int age;
public GsonTest(String string, int i) {
this.name=string;
this.age=i;
}
public static void main(String [] arge) {
Gson gson = new Gson();
GsonTest test_tojson = new GsonTest("你好",23);
String jsonObject = gson.toJson(test_tojson);
System.out.println(jsonObject);
}
}
留言列表