我正在尝试获取一个api,我是新手。我可以获取json外部的数据,但我不知道如何显示嵌套在数组内部的数据。例如,我正在尝试从PokeApi获取数据
我正在尝试获取类型内的所有数据。
package org.example;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
Scanner scan = new Scanner(System.in);
String name;
System.out.println("Enter a pokemon name:");
name = scan.nextLine();
Transcript transcript = new Transcript();
Gson gson = new Gson();
String jsonRequest = gson.toJson(transcript);
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest getRequest = HttpRequest.newBuilder()
.uri(new URI("https://pokeapi.co/api/v2/pokemon/"+name))
.header("Auth","abc")
.GET()
.build();
HttpResponse<String> getResponse =httpClient.send(getRequest, BodyHandlers.ofString());
transcript = gson.fromJson(getResponse.body(),Transcript.class);
System.out.println("Pokemon name: "+transcript.getName());
}
}
上面是我的主文件,下面是我的成绩单类
package org.example;
public class Transcript {
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private int id;
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
private int height;
private int order;
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
private int weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我为我糟糕的英语感到抱歉
1条答案
按热度按时间n3h0vuf21#
对于嵌套的JSON对象,您需要定义适当的Java类,并使它们成为父类的字段,例如,在Json中您有:
您需要一个
并使其成为“根”类的字段
这是一个非常简单的例子。