gson 處理泛型

來源:互聯網
上載者:User

解析json, 我只喜歡簡單的東西,gson比較簡單,我一直用它,今天碰到了處理泛型時的問題

使用的實體類如下:

1
class Option {
2
    public String itemValue;
3
    public String itemLabel;
4
 
5
    public Option(String itemValue, String itemLabel) {
6
        this.itemValue = itemValue;
7
        this.itemLabel = itemLabel;
8
    }
9
}
(1)將List變成json字串


1
List<Option> options = new ArrayList<Option>();
2
options.add(new Option("1", "男"));
3
options.add(new Option("2", "女"));
4
Gson gson = new Gson();
5
String json = gson.toJson(options, List.class);
6
System.out.println(json);

列印出[{"itemValue":"1","itemLabel":"男"},{"itemValue":"2","itemLabel":"女"}]

(2)將上面的字串轉成List

1
String json = 上面的輸出
2
Gson gson = new Gson();
3
List<Option> options = gson.fromJson(json,List.class);
4
for (Iterator it = options.iterator(); it.hasNext();) {
5
    Option option = (Option) it.next();
6
    System.out.println(option.itemLabel);
7
}

報錯如下:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to
Option

改成

1
Gson gson = new Gson();
2
List<Option> options = gson.fromJson(json,new TypeToken<List<Option>>(){}.getType());
3
for (Iterator it = options.iterator(); it.hasNext();) {
4
    Option option = (Option) it.next();
5
    System.out.println(option.itemLabel);
6
}
成功!
 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.