如何将对象添加到ArrayList

时间:2019-06-23 05:14:46

标签: android arrays json

我无法将对象添加到从API端点接收的ArrayList中。我正在尝试从JsonArray制作JSONObject

mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, ENDPOINT, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            mJsonArray=response.getJSONArray("articles");
            for(int i=0;i<mJsonArray.length();i++){
                mJsonObject=mJsonArray.getJSONObject(i);
                model = new Model();
                model.setTitle(mJsonObject.getString("title"));
                model.setAuthor(mJsonObject.getString("author"));
                model.setDescription(mJsonObject.getString("description"));

                Toast.makeText(MainActivity.this, "" + model.getTitle(), Toast.LENGTH_SHORT).show(); // returns 0

                mModelList.add(model);
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
};

2 个答案:

答案 0 :(得分:0)

您可以使用Gson库,它将为您完成辛苦的工作。

例如:

这是您的json String

"[{'Title':'admin','Name':'eddie'},{'Title':'manager','Name':'frank'}]"

这是您的POJO:

 class Model {
    public String Title;
    public String Name;
}

并按以下方式使用它:

Gson g = new Gson();
    ArrayList<Model> i = g.fromJson("[{'Title':'title','Name':'name'},{'Title':'title','Name':'name'}]", new ArrayList<Model>().getClass());
    Toast.makeText(this, String.valueOf(i.size()), Toast.LENGTH_SHORT).show();

答案 1 :(得分:0)

您需要使用object.optString("code")来捕获响应,否则需要POJO类。我根据您的意思推荐一种解决方案

mJsonObjectRequest=new JsonObjectRequest(Request.Method.GET, ENDPOINT, null, 
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
                if (response.isSuccessful() && response.code() == 200) {
                    JSONObject jsonObject = new 
                    JSONObject(response.body().string());
                    JSONArray jsonArray = jsonObject.optJSONArray("data");
                    if (jsonArray.length() > 0) {
                        db.clearData();
                    }
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.optJSONObject(i);
                        db.insertConfig(new ConfigModel(object.optInt("id"), object.optString("code"), object.optString("value"), object.optString("createdAt"), object.optString("updatedAt")));
                    }
                }
            } catch (Exception ex) {
                utility.logger(ex.toString());
            }