How to retrieve an unnamed json array

RafaelB13 :

I'm using this url:

https://jsonplaceholder.typicode.com/posts

I want to recover the title and body of this json, but when I pass

JSONArray postArrayJson = jsonObject.getJSONArray("");

It doesn't work...

This is the function I'm using:

private List<Post> getPosts(JSONObject jsonObject) throws JSONException {
        List<Post> posts = new ArrayList<>();

        JSONArray postArrayJson = jsonObject.getJSONArray("");
        for (int i = 0; i < postArrayJson.length(); i++) {

            JSONObject postArrayJsonJSONObject = postArrayJson.getJSONObject(i);

            String title = postArrayJsonJSONObject.getString("title");
            String body = postArrayJsonJSONObject.String("body");

            Post postsObj = new Post();
            postsObj.setTitle(body);
            postsObj.setBody(title);
            posts.add(postsObj);

        }
        return posts;
    }

I get her back here:

JSONObject jsonObject = new JSONObject(jsonAsString);

List<Post> posts = getPosts(jsonObject);

All code:

public class JsonPostTask extends AsyncTask<String, Void, List<Post>> {

    private final WeakReference<Context> context;
    private ProgressDialog dialog;
    private PostLoader postLoader;
    private BufferedInputStream is;

    public JsonPostTask(Context context) {
        this.context = new WeakReference<>(context);
    }

    public void setPostLoader(PostLoader postLoader) {
        this.postLoader = postLoader;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        Context context = this.context.get();
        if(context != null)
            dialog = ProgressDialog.show(context, "Carregando", "", true);
    }

    @Override
    protected List<Post> doInBackground(String... params) {
        String url = params[0];

        try {
            URL requestUrl = new URL(url);
            HttpsURLConnection urlConnection = (HttpsURLConnection) requestUrl.openConnection();
            urlConnection.setReadTimeout(2000);
            urlConnection.setConnectTimeout(2000);

            int responseCode = urlConnection.getResponseCode();
            if (responseCode > 400)
                throw new IOException("Erro na comunicação com o servidor remoto");

            InputStream inputStream = urlConnection.getInputStream();

            is = new BufferedInputStream(urlConnection.getInputStream());

            String jsonAsString = toString(is);
            JSONArray jsonObject = new JSONArray(jsonAsString);



            List<Post> posts = getPosts();

            is.close();

            return posts;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private List<Post> getPosts() throws JSONException, IOException {

        String jsonAsString = toString(is);

        JSONArray postArrayJson = new JSONArray(jsonAsString);

        List<Post> posts = new ArrayList<>();

        for (int i = 0; i < postArrayJson.length(); i++) {

            JSONObject postArrayJsonJSONObject = postArrayJson.getJSONObject(i);
            String title = postArrayJsonJSONObject.getString("title");
            String body = postArrayJsonJSONObject.getString("body");
            Post postsObj = new Post();
            postsObj.setTitle(body);
            postsObj.setBody(title);
            posts.add(postsObj);
        }




        return posts;
    }

    private String toString(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[1024];

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int alreadyRead;
        while ((alreadyRead = inputStream.read(bytes)) > 0) {
            byteArrayOutputStream.write(bytes, 0, alreadyRead);
        }

        return new String(byteArrayOutputStream.toByteArray());
    }


    @Override
    protected void onPostExecute(List<Post> posts) {
        super.onPostExecute(posts);

        dialog.dismiss();
        if (postLoader != null)
            postLoader.onResult(posts);

    }
}
IntelliJ Amiya :
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }

You should use new JSONArray() because your JSON already is an Array .

Don't

JSONArray postArrayJson = jsonObject.getJSONArray("");

Do

 JSONArray postArrayJson = new JSONArray(jsonResponse);
   for (int i = 0; i < postArrayJson.length(); i++) {

   }

Change here

private List<Post> getPosts(JSONArray jsonResponse) throws JSONException {

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169875&siteId=1