请帮助解析json以使用Volley进行建模

时间:2019-01-07 06:18:35

标签: android json android-volley

我有json这样的人

{
    "message": "success",
    "battery": "AHAJAJ1DH13T0021",
    "data": {
        "id": 6,
        "userId": 3,
        "shopId": 1,
        "transactionStatus": "PENDING",
        "expiredAt": "2019-01-04T03:01:18.878Z",
        "updatedAt": "2019-01-04T02:01:18.916Z",
        "createdAt": "2019-01-04T02:01:18.916Z",
        "paymentId": null,
        "batteryNo": null
    }
}

这是我的模型课

public class BookBattery implements Serializable {

private int id;
private String ebikeSn;
private String bookTime;
private String batterySn;
private String transactionStatus;
private String paymentId;
private String batteryNo;
private String addressBook;
private int leftSeconds;

这是我的适配器

public class BookBatteryListAdapter extends RecyclerView.Adapter {

private Context mContext;
private List<BookBattery> mBookBatteryList = new ArrayList<>();

public BookBatteryListAdapter(Context context) {
    mContext = context;
}

public void setList(List<BookBattery> bookBatteryList) {
    mBookBatteryList.clear();
    mBookBatteryList.addAll(bookBatteryList);
    notifyDataSetChanged();
}

public void clear() {
    mBookBatteryList.clear();
    notifyDataSetChanged();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View inflate = LayoutInflater.from(mContext)
            .inflate(R.layout.item_book_battery, parent, false);
    return new ViewHolder(inflate);
}

......

并且已经生成了setter和getter,我想问一下如何将json从服务器解析到我的类中,然后我可以在recyclerview中显示到显示结果中吗??

1 个答案:

答案 0 :(得分:0)

例如,您可以在此处解析您的JSON

JSONObject responseObj = new JSONObject(response);
JSONObject dataObj = responseObj.getJSONObject("data");

然后在这里通过解析数据对象内部的字段来完成操作。

int id = dataObj.getInt("id");
String transactionStatus = dataObj.getString("transactionStatus");

同样,您可以对所有字段进行操作。

然后为您Model Class Object设置数据。

BookBattery bookBattery = new BookBattery();
bookBattery.setId(id);

同样,您可以设置所有数据并将其添加到List<BookBattery>并将其设置为RecyclerView Adapter