數組我想反序列化複雜的對象GSON反序列化複雜的對象
例如數組我有對象MyTestObject
public class MyTestObject{
String param1;
String param2;
int param3;
}
現在我有對象的數組命名MyTestObject
和我的json看起來像這樣
{
[
"param1":"something1",
"param2:"something2",
"param3":3
],
[
"param1":"something1",
"param2:"something2",
"param3":3
],
[
"param1":"something1",
"param2:"something2",
"param3":3
]
}
這是我desearilization
public static <T> List<T> fromJSON(String json, Class<T> className) {
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Type myType = new TypeToken<List<T>>() {
}.getType();
Gson g1 = builder.create();
List<T> objects = (List<T>) g1.fromJson(json, (Type) myType);
for (T object : objects) {
Log.d(TAG, "object: " + object + " class " + object.getClass());
}
return objects;
}
ArrayList<MyTestObject> objects = fromJSON(myjson,MyTestObject.class);
代碼數組本身被反序列化正確的,但是,它裏面的對象是一個正確的類一樣,他們是類型com.google.gson.internal.LinkedTreeMap
,當我需要他們的類型MyTestObject
我該如何解決這個問題?
這可能有助於http://stackoverflow.com/questions/17231298/serializing-a-sparsearrayt-with-gson – Tala
這不是有效的JSON!你不能擁有這個'{[...],[......]}',但是你需要這個'{'foo':[']'bar':[。 ..],'baz':[...]}'...我的意思是,根對象中的數組必須有一個名稱... – MikO