1. 程式人生 > >Gson的使用以及Json、Bean、Map、List之間的轉換

Gson的使用以及Json、Bean、Map、List之間的轉換

1、使用Gson將String(json)轉換成bean:

String data = bundle.getString("cardData");
Gson gson = new Gson();
CheckOrderBean orderBean = gson.fromJson(data, CheckOrderBean.class);

2、將bean物件轉換為json字串

BonusBean bean = orderBean.getData().getBonus();

String cardStr = gson.toJson(bean, BonusBean.class)

3、JSON轉換為Map:

Map<String, CheckOrderBean.DataBean.BonusBean._$72522Bean> cardMap = gson.fromJson(cardStr, new TypeToken<Map<String, CheckOrderBean.DataBean.BonusBean._$72522Bean>>() {}.getType());

4、Map轉List:

Map<String, String> testMap = orderBean.getData().getBonus();

List<CheckOrderBean.DataBean.BonusBean._$72522Bean> list = new ArrayList();
Iterator iter = testMap.entrySet().iterator(); // 獲得map的Iterator
while (iter.hasNext()) {
    Map.Entry entry = (Map.Entry) iter.next();
    CheckOrderBean.DataBean.BonusBean._$72522Bean bean = (CheckOrderBean.DataBean.BonusBean._$72522Bean)entry.getValue();
    list.add(bean);
}