【问题标题】:JSON strings to collection Java用于收集 Java 的 JSON 字符串
【发布时间】:2014-02-25 21:33:50
【问题描述】:

我有 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);

}

此时collection中的数据类型不是Examp,而是LinkedTreeMap。 我有一个问题。 如何访问这些数据(例如姓名)?

【问题讨论】:

    标签: java json deserialization gson json-deserialization


    【解决方案1】:

    你需要一个TypeToken

    ArrayList<Examp> collection = gson.fromJson(str, new TypeToken<ArrayList<Examp>>(){}.getType());
    

    TypeToken 是一种获取泛型类型使用的泛型类型参数的泛型黑客。

    请注意,您将无法将TypeToke 与类型变量一起使用。 (你可以使用它,但不会得到你想要/期望的东西)。

    【讨论】:

    • @Xwar 不客气。考虑接受或支持有用的答案。
    【解决方案2】:

    你需要使用TypeToken:

    Type type = new TypeToken<ArrayList<Examp>>() {}.getType();
    List<Examp> collection = gson.fromJson(json, type );
    

    参考他们的wiki page:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2017-11-28
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      相关资源
      最近更新 更多