下面是關於如何將Gson與對象列表一起使用的全面示例。這應該證明究竟如何轉換到/從JSON,如何引用列表等
Test.java:
import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Test {
public static void main (String[] args) {
// Initialize a list of type DataObject
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(0, "zero"));
objList.add(new DataObject(1, "one"));
objList.add(new DataObject(2, "two"));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>(){}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i=0;i<inpList.size();i++) {
DataObject x = inpList.get(i);
System.out.println(x);
}
}
private static class DataObject {
private int a;
private String b;
public DataObject(int a, String b) {
this.a = a;
this.b = b;
}
public String toString() {
return "a = " +a+ ", b = " +b;
}
}
}
要編譯:
javac -cp "gson-2.1.jar:." Test.java
而且最後運行它:
java -cp "gson-2.1.jar:." Test
請注意,如果您使用Windows,則必須在前兩個命令中使用;
切換:
。
在運行它,你應該看到下面的輸出:
[{"a":0,"b":"zero"},{"a":1,"b":"one"},{"a":2,"b":"two"}]
a = 0, b = zero
a = 1, b = one
a = 2, b = two
請記住,這僅僅是一個命令行程序演示它是如何工作的,但同樣的原則也適用內Android的環境(引用的jar庫等)
嘗試'字符串JSON =新GSON()的toJSON(數據對象)',其中數據對象是DataObject中[] – reTs 2012-02-08 02:41:03