简体   繁体   中英

How to parse json array in retrofit

I want to parse the array but I am not able to get the pdf file from 0 INDEX. Here is my code snippet:

 @Override
                public void onResponse(JSONObject response) {
                    // response
                    Gson gson = new Gson() ;
                    MagazineResponseModel bookResponseModel;
                    bookResponseModel = gson.fromJson(response.toString(),MagazineResponseModel.class);
                    listGridViewBooks.addAll(bookResponseModel.getBooks());
                    mGridView.setAdapter(new MagazineGridViewAdapter(getActivity(),
                            R.layout.custom_books_view, listGridViewBooks));

                }

Here is the JSON response, i want to parse the first item of file array

{"file": [
  "file1.pdf",
  "file2.pdf"
]  }
{
  "file": [
      "file1.pdf",
      "file2.pdf"
    ]  
}

This would be the best way to get the json object.

Then, you can do this....

    JSONObject object = new JSONObject(jsonData);
    
    System.out.println(object);
    
    JSONArray file = object.getJSONArray("file");
    System.out.println(file);
    
    for (int i = 0; i < file.length(); i++) {
        System.out.println(file.get(i));
    }

It would print this.

{"file":["file1.pdf","file2.pdf"]}

["file1.pdf","file2.pdf"]

file1.pdf

file2.pdf

 JSONArray fileArray = bookObject.getJSONArray("file");
 for (int j = 0; j<fileArray.length(); j++){
 JSONArray nestedFileArray = fileArray.getJSONArray(j);                                       
 YOUR_MODEL.setFile(nestedFileArray.getString(YOUR_FILE_POSITION));}

I re-write the @droiDev answer for better results

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