简体   繁体   English

如何使用 Java 在屏幕上打印 JSON 文件的值?

[英]How to print a value of a JSON file on the screen with Java?

I recently started using the OKHttp library to make requests to an API, this is the code:我最近开始使用 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();
}

Now, I would like to know how to print the value that has the string "firstname" as the "key".现在,我想知道如何打印以字符串“firstname”作为“key”的值。

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

I think this should work for you.我认为这应该对你有用。

You should get the String from Response :您应该从Response获取字符串:

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

Then you have to parse the JSON contained in the String.然后你必须解析包含在字符串中的 JSON。 For this, you can use org.json :为此,您可以使用 org.json :

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

Or maybe use Jackson to parse JSON if you can map your JSON to an class you have.或者,如果您可以将 JSON 映射到您拥有的类,则可以使用 Jackson 来解析 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM