【问题标题】:How to print a value of a JSON file on the screen with Java?如何使用 Java 在屏幕上打印 JSON 文件的值?
【发布时间】:2020-02-28 14:46:16
【问题描述】:

我最近开始使用 OKHttp 库向 API 发出请求,代码如下:

public static void main(String[] args) throws IOException {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
        .url("https://api-football-v1.p.rapidapi.com/v2/players/player/874")
        .get()
        .addHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com")
        .addHeader("x-rapidapi-key", "6147bd5da4mshfacf56a7067aa5ep1ff9e6jsn60984dedb281")
        .build();

    okhttp3.Response response = client.newCall(request).execute();
}

现在,我想知道如何打印以字符串“firstname”为“key”的值。

【问题讨论】:

    标签: java json api


    【解决方案1】:

    您应该从Response 获取字符串:

    String stringResponse = response.body().string();
    

    然后你必须解析字符串中包含的 JSON。 为此,您可以使用 org.json :

    JSONObject jsonResponse = new JSONObject(stringResponse);
    String firstName = jsonResponse.getString("firstName");
    

    如果您可以将 JSON 映射到您拥有的类,也可以使用 Jackson 来解析 JSON。

    【讨论】:

      【解决方案2】:

      JSONObject responseJson = new JSONObject(response); String firstname = responseJson .get("firstname").toString();

      我认为这应该适合你。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多