如何使用Java在屏幕上打印JSON文件的值?
我最近开始使用OKHttp库向API发出请求,代码如下:如何使用Java在屏幕上打印JSON文件的值?,java,json,api,Java,Json,Api,我最近开始使用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
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”的值; 字符串firstname=responseJson.get(“firstname”).toString()
我认为这应该适合您。您应该从
响应中获取字符串:
String stringResponse = response.body().string();
然后必须解析字符串中包含的JSON。
为此,您可以使用org.json:
JSONObject jsonResponse = new JSONObject(stringResponse);
String firstName = jsonResponse.getString("firstName");
或者,如果可以将JSON映射到现有的类,可以使用Jackson解析JSON