使用 GsonFormat 解析数组形式的 json

记下笔记,以访忘记

假设有以下数据

[{
    "CarId": 1,
    "Time": "2017-11-26 16:58:11",
    "Cost": 10
}, {
    "CarId": 1,
    "Time": "2017-11-26 16:58:19",
    "Cost": 20
}, {
    "CarId": 1,
    "Time": "2017-11-26 16:58:24",
    "Cost": 30
}, {
    "CarId": 1,
    "Time": "2017-11-26 16:58:28",
    "Cost": 40
}]

以下类

public class GetCarAccountRecord {

    /**
     * CarId : 1
     * Time : 2017-11-26  04:58:11
     * Cost : 10
     */

    private int CarId;
    private String Time;
    private int Cost;

    public int getCarId() {
        return CarId;
    }

    public void setCarId(int CarId) {
        this.CarId = CarId;
    }

    public String getTime() {
        return Time;
    }

    public void setTime(String Time) {
        this.Time = Time;
    }

    public int getCost() {
        return Cost;
    }

    public void setCost(int Cost) {
        this.Cost = Cost;
    }
}

使用 Gson 解析,然后遍历输出

List<GetCarAccountRecord> list = new Gson().fromJson(jsonObject.optJSONArray("ROWS_DETAIL").toString(), new TypeToken<List<GetCarAccountRecord>>() {}.getType());

for (GetCarAccountRecord getCarAccountRecord : list) {
    Log.i("小车编号:", String.valueOf(getCarAccountRecord.getCarId()));
    Log.i("充值金额:", String.valueOf(getCarAccountRecord.getCost()));
}

如无特别声明,该文章均为 现在网NowTime.cc)原创,转载请遵循 署名-非商业性使用 4.0 国际(CC BY-NC 4.0) 协议,即转载请注明文章来源。


标签: Android, Java, Gson, Java Bean

赞 (0)

添加新评论