我有 JSON 字符串
例如
[{
"id":"abc",
"name":"ffa",
"done":0
},
{
"id":"abc",
"name":"ffa",
"done":0
}]
我想将此 JSON 转换为 Examp 类的集合。 我尝试过使用 gson。
public static void main(String[] args)
{
Gson gson = new Gson();
Examp a=new Examp(); //Class Examp have 3 fields (id,name,done)
Examp b=new Examp();
a.done=0;
b.done=0;
a.id="foo";
b.id="foo1";
a.name="faa";
b.name="faa1";
ArrayList<Examp> arr= new ArrayList<Examp>();
arr.add(b);
arr.add(a);
String str = gson.toJson(arr);
System.out.println(str); //format check
ArrayList<Examp> collection = gson.fromJson(str, ArrayList.class);
}
此时集合中的数据类型不是Examp,而是LinkedTreeMap。 我有一个问题。 我如何访问这些数据(例如姓名)?
最佳答案
您需要一个TypeToken
ArrayList<Examp> collection = gson.fromJson(str, new TypeToken<ArrayList<Examp>>(){}.getType());
TypeToken
是一种通用黑客,用于获取泛型类型使用的泛型类型参数。
请注意,您将无法将 TypeToke
与类型变量一起使用。 (您将能够使用它,但不会得到您想要/期望的东西)。
关于java - JSON 字符串到集合 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22026719/