如何在Java中通过API响应获取String Json?我试图将它们解析为Object,但我没有工作
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();
}
}发布于 2020-07-21 17:18:35
您的Response对象应该有一个body()方法,该方法允许您检索已响应您的调用的内容。
您的代码应如下所示:
try (Response response = client.newCall(res).execute();
ResponseBody body = response.body()) {
Data data = gson.fromJson(body.string(), Data.class);
} catch (IOException e) {
e.printStackTrace();
}https://stackoverflow.com/questions/63011151
复制相似问题