Gson常用解析方法

1.很多单条数据,先构造函数,放入list里面

List<FinancialProduct.RowsEntity> productList = new ArrayList<FinancialProduct.RowsEntity>();

FinancialProduct productInfo = GsonUtils.jsonToBean(
        json, FinancialProduct.class
);
for (int i = 0; i < productInfo.getRows().size(); i++) {
    FinancialProduct.RowsEntity one = new FinancialProduct.RowsEntity(
            productInfo.getRows().get(i).getProductid(),
            productInfo.getRows().get(i).getProductname(),
            productInfo.getRows().get(i).getRate(),
            productInfo.getRows().get(i).getEnddate(),
            productInfo.getRows().get(i).getResidualrate(),
            productInfo.getRows().get(i).getState(),
            productInfo.getRows().get(i).getAgreementid()
    );
    productList.add(one);
}

2.分别放入list

List<String> imageUrls = new ArrayList<String>();

private List<String> mAdvertisementsList = new ArrayList<String>();

Advertisement adInfo = GsonUtils.jsonToBean(
        json, Advertisement.class
);
for (int i = 0; i < adInfo.getRows().size(); i++) {
    imageUrls.add(adInfo.getRows().get(i).getPicurl());
    mAdvertisementsList.add(adInfo.getRows().get(i).getArticleurl());
}
3.直接把json转换成list

/**
 * 把json字符串解析到List
 *
 * @param msg
 *
 * @return
 */
private List<MyProductInfo> parserStrToGson(String msg) {
    // 创建一个Gson对象
    Gson gson = new Gson();
    // 记号:按List<MyProductInfo>来进行字符串解析
    TypeToken<List<MyProductInfo>> token = new TypeToken<List<MyProductInfo>>() {};
    // 将GSON格式的字符串转为指定的格式
    System.out.println(msg);
    return gson.fromJson(msg, token.getType());}
4.分别赋值
public List<MessageInfo> messageInfoList = new ArrayList<MessageInfo>();
public List<MessageInfo> mList = new ArrayList<MessageInfo>();
private long createTime[] = new long[200];
private String content[] = new String[200];
messageInfoList = parserStrToGson(json);
for (int i = 0; i < messageInfoList.size(); i++) {
    createTime[i] = messageInfoList.get(i).getCreatetime();
    content[i] = messageInfoList.get(i).getContent();
}
for (int i = 0; i < messageInfoList.size(); i++) {
    mList.add(
            new MessageInfo(
                    content[i], createTime[i]
            )
    );
}

猜你喜欢

转载自blog.csdn.net/u010111008/article/details/51869099