2

How can I get String Json by Response from API in Java? I am trying to get And Parse them to Object but I not work

public class tedst {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        Gson gson = new Gson();
        Request res = new Request.Builder().url("http://api.openweathermap.org/data/2.5/weather?q=Hanoi&APPID=bffca17bcb552b8c8e4f3b82f64cccd2&units=metric").build();
        try {
            Response response = client.newCall(res).execute();
           Data data = gson.fromJson(response.toString(), Data.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
1
  • Please, can you accept the answer I gave to help others? Commented Jul 23, 2020 at 12:54

1 Answer 1

1

Your Response object should have a body() method that lets you retrieve what has been responded to your call.

Your code should look like this:

try (Response response = client.newCall(res).execute();
     ResponseBody body = response.body()) {
    Data data = gson.fromJson(body.string(), Data.class);
} catch (IOException e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

1 Comment

You are my Angel. Thanks so much <3

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.