How to extract JSON data from okhttp3 Response object in Android API 28

I have this working code that sends a POST request to my API:

private class ApiDataSender extends AsyncTask<URL, Integer, Long> {
    @Override
    protected Long doInBackground(URL... urls) {

        Gson gsonParser = new GsonBuilder().create();
        String requestJson = gsonParser.toJson(dataRequest);

        OkHttpClient httpClient = createHttpClient();
        RequestBody requestBody;
        Request apiRequest;

        MediaType jsonType = MediaType.parse("application/json; charset=UTF-8");
        requestBody = RequestBody.create(jsonType, requestJson);
        apiRequest = new Request.Builder()
                .url("my-api-endpoint")
                .method("POST", requestBody)
                .addHeader("Content-Type", "application/json; charset=UTF-8")
                .build();

        try {
            Response apiResponse = httpClient.newCall(apiRequest).execute();

            //------Need to parse response data here--------

        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }
}

I execute this with new ApiDataSender().execute()

My server returns JSON like this: return new JsonResult(new { message = "success", status = "OK" })

The problem is I don’t know how to get the actual JSON string from the apiResponse variable which is of type okhttp3.Response. What method should I use to read the response body content?

The main thing that tripped me up with OkHttp was handling ResponseBody correctly. Once you get your Response object, call apiResponse.body().string() to grab the raw JSON. Just make sure you wrap it in try-catch - the string() method throws IOException. Since ResponseBody implements Closeable, I’d use try-with-resources too. After that, your Gson parser handles the rest. I usually create a wrapper class that matches what the server sends back, then parse straight into that rather than messing with raw JSON strings.

just call apiResponse.body().string() for the json string, then use gson to parse it like this: MyResponseClass response = gsonParser.fromJson(jsonString, MyResponseClass.class) but make sure to close the response afterward.

Use apiResponse.body().string() to extract the JSON data. First check if the response worked with apiResponse.isSuccessful(). Don’t forget to close the response when you’re done or you’ll get memory leaks. I always check the response code first, then read the body string and parse it with Gson. Heads up - you can only call body().string() once per response, so save the result if you need it multiple times.