2

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);

    }
}
2
  • 1
    Please post full code Commented Mar 7, 2020 at 13:16
  • @Ashish There, my friend! Commented Mar 7, 2020 at 13:44

1 Answer 1

3
[
  {
    "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 {
Sign up to request clarification or add additional context in comments.

1 Comment

it happens: W/System.err: org.json.JSONException: Not a primitive array: class org.json.JSONArray at org.json.JSONArray.<init>(JSONArray.java:116) W/System.err: at com.rf1.showposts.utils.JsonPostTask.getPosts(JsonPostTask.java:98) at com.rf1.showposts.utils.JsonPostTask.doInBackground(JsonPostTask.java:80) at com.rf1.showposts.utils.JsonPostTask.doInBackground(JsonPostTask.java:31) at android.os.AsyncTask$2.call(AsyncTask.java:333)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.