【问题标题】:Get JSON String from API java从 API java 获取 JSON 字符串
【发布时间】:2020-11-10 15:14:38
【问题描述】:

如何通过 Java 中的 API 响应获取字符串 Json? 我正在尝试将它们解析为对象,但我不工作

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

【问题讨论】:

  • 拜托,你能接受我给帮助别人的答案吗?

标签: java json api okhttp


【解决方案1】:

您的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();
}

【讨论】:

  • 你是我的天使。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 2022-09-24
  • 2012-04-15
  • 2016-03-12
相关资源
最近更新 更多