我将 ArrayList
转换为 JSON String
并将其保存到 File
中。这非常有效。但是,如果我尝试反向执行此操作,我的应用程序将无法运行(我得到类似 ClassCastException
的信息)
有人能告诉我我的代码有什么问题吗?
BufferedReader br = new BufferedReader(
new FileReader("/sdcard/file.json"));
myArrayList = gson.fromJson(br, ArrayList.class);
最佳答案
这是一个 SSCCE执行并演示了如何取回类型化的 ArrayList
:
public static void main(String args[]) {
Gson gson = new Gson();
List<Integer> outList = new ArrayList<Integer>();
outList.add(1);
outList.add(2);
outList.add(3);
String json = gson.toJson(outList);
// This is how you tell gson about the generic type you want to get back:
Type type = new TypeToken<ArrayList<Integer>>(){}.getType();
ArrayList<Integer> inList = gson.fromJson(json, type);
for (int i : inList) {
System.out.println(i);
}
}
输出:
1
2
3
这段代码没有爆炸的事实证明 ArrayList
实际上是正确输入的。
我不是通过文件将示例简化到最低限度。
关于java - 从 Java 中的 JSON 字符串获取类型化的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7307487/