简体   繁体   中英

Get an arraylist from JSON response

i have a node js API and i am using Volley to get JSON response from it into android , the API returns a result of a select query and i need to get this result in an Arraylist of objects 'News' in the android part . this is the node js API part :

    connection.query("SELECT * FROM news",
        function(err,rows,fields){
       if (!err){
        if (rows.length > 0){
            res.setHeader('Content-Type', 'application/json');
            res.send(rows);
        }
        else{
            var error = {msg: "news is empty"}
            res.send(error);
        }
    }

});

this is the android part where i need to get the 'rows' from the json response in an arraylist :

  String URLnews = "http://10.0.2.2:3000/getnews";
        RequestQueue requestQueueNews = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequestNews = new JsonObjectRequest(
                Request.Method.GET,
                URLnews,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject responsenews) {
                        Log.e("news length",responsenews.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Rest Response",error.toString());
                    }
                }
        );


        requestQueueNews.add(objectRequestNews);

this is the JSON response :

[
    {"idnews":1,"content":"news first news","image":"img"}, 
    {"idnews":2,"content":"news 2","image":"img2"}
]

notice that the API is working correctly it's returning the results but as a String as printed in android , but i need to get every row in a seperated object in an arraylist is that possible ?

Because your JSON object within JSON array, so you need to change your JsonObjectRequest to JsonArrayRequest.

new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray responsenews) {
                    try {
                          for (int i = 0; i < responsenews.length(); i++) {
                              JSONObject object = responsenews.getJSONObject(i);
                              int id = object.getInt("idnews");
                              String content = object.getString("content");
                              String image = object.getString("image");
                        }
                    }catch (JSONException e) {
                         e.printStackTrace();
                    }
                }
            }

Here what you are missing is the conversion from JSON. You could use GSON, for example, to get the job done.

new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray responsenews) {
          Log.e("news length",responsenews.toString());
          Gson gson = new Gson();
          Type type = new TypeToken<List<News>>() {}.getType();
          List<News> news = gson.fromJson(responsestr, listType);
       }
    },

You will need to define the News class, and that should be all.

NOTE: Answer has been updated to reflect the fact that valentino correctly noticed, that is should be a JSONArray request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM