【发布时间】:2011-08-24 03:46:27
【问题描述】:
我在ParentClass 内有一个ArrayList<CustomClass>,我已使用Gson.toJson() 将其写入文件。但是,当我尝试使用 Gson.fromJson() 反序列化 JSON 时,我只得到 ArrayList<CustomClass> 的 1 个元素。
例如,我将执行以下操作
public class ParentClass {
private ArrayList<CustomClass> myList = new ArrayList<CustomClass>();
private GrandParentClass nested;
public ParentClass() {
myList.add(new CustomClass("adsf"));
myList.add(new CustomClass("fdsa"));
nested = new GrandParentClass();
}
public int arraySize() {
return myList.size();
}
}
public class GrandParentClass {
private ArrayList<OtherCustomClass> myList = new ArrayList<OtherCustomClass>();
public GrandParentClass() {
myList.add(new CustomClass("asdfasdf.."));
myList.add(new CustomClass("fdsafdsa..."));
}
public int arraySize() {
return myList.size();
}
}
然后当我实例化一个新的 ParentClass 实例时,我使用以下内容将其写入文件。
ParentClass pc = new ParentClass();
Gson gson = new Gson();
String writeThis = gson.toJson(pc); // Produces a perfect JSON reflection myList
FileOutputStream fos = new FileOutputStream(new File("writeto.json"));
fos.write(writeThis);
fos.close();
JSON 对象以纯文本形式写入 .json 文件
FileInputStream fis = new FileInputStream(new File("writeto.json"));
char c;
StringBuffer sb = new StringBuffer();
while ((c = fis.read()) != -1)
sb.append((char) c);
//Now this is where I only get 1 element of the ArrayList
Gson gson = new Gson();
ParentClass pc = gson.fromJson(sb.toString(), ParentClass.class);
Log.i("SIZE", "Size is " + pc.arraySize()); // Log output: 'Size is 1'
现在,即使我已验证 JSON 文件中的 ArrayList 中确实有两个元素,但使用 fromJson 将只有 1 个元素加载到对象中。
我序列化这些就好了,但是我想一举反序列化GrandParentClass 内部的ArrayList<OtherCustomClass>,它位于ParentClass 内部。
基本上我想序列化 ArrayLists 在这个对象层次结构中可能嵌套 3 或 4 层,并将它们反序列化为包含这些嵌套 ArrayLists<?> 的 1 个 ParentClass。这将如何实现?
谢谢
【问题讨论】:
-
只是出于好奇,您为什么选择使用 GSON?我一直在使用jackson 来提高解析速度。我只是想知道是否值得花时间研究 GSON。