我尝试使用一些网络 API,所以我这样做
public static void main(String[] args) {
// Create Jersey client
Client client = Client.create();
// GET request to findBook resource with a query parameter
String getSoccersSeasonsUrl = "http://api.football-data.org/v1/soccerseasons";
WebResource webResourceGet = client.resource(getSoccersSeasonsUrl);
webResourceGet.header("X-Auth-Token", myToken);
ClientResponse response = webResourceGet.get(ClientResponse.class);
String output = response.getEntity(String.class);
System.out.println(output);
}
输出
[{"_links":{"self":{"href":"http://api.football-data.org/v1/soccerseasons/394"},"teams":{"href":"http://api.football-data.org/v1/soccerseasons/394/teams"},"fixtures":{"href":"http://api.football-data.org/v1/soccerseasons/394/fixtures"},
"leagueTable":{"href":"http://api.football-data.org/v1/soccerseasons/394/leagueTable"}},
"id":394,
"caption":"1. Bundesliga 2015/16",
"league":"BL1",
"year":"2015",
"currentMatchday":24,
"numberOfMatchdays":34,
"numberOfTeams":18,
"numberOfGames":306,
"lastUpdated":"2016-03-01T20:50:44Z »}
如何直接将此输出填充到对象的 java ArrayList 中,例如:
public class SoccerSeason {
public SoccerSeason() {
}
private long id;
private String caption;
private String league;
private String year;
private long currentMatchday;
private long numberOfMatchdays;
private long numberOfTeams;
private long numberOfGames;
private String lastUpdated;
}
当我尝试直接获取 SoccerSeason 输出 = response.getEntity(SoccerSeason.class);我有一个经典的 com.sun.jersey.api.client.ClientHandlerException 请问我的代码中缺少什么?你知道如何简单地做到这一点吗?
最佳答案
你想要的是Google的GSON。通过快速谷歌搜索就可以找到它,并且它有大量易于阅读的文档。
将 GSON 添加到您的项目依赖项/源代码中,将所有类成员的 getter 和 setter 添加到您创建的类中,它应该可以正常工作。
它的用法如下:
Gson gson = new Gson();
SoccerSeason newSoccerSeason = gson.fromJson(webApiResponse, SoccerSeason.class);
String lastUpdated = newSoccerSeason.getLastUpdated();
其中 webApiResponse
是作为 Web API 响应收到的 JSON 的字符串表示形式。您还可以定义一个 SoccerSeasonList
类,如下所示:
public class SoccerSeasonList {
ArrayList<SoccerSeason> seasonList;
// getters/setters
}
当然,您传入的 JSON 必须有一个名为 seasonList 的对象,其中包含所有 SoccerSeason
对象,以与此定义匹配。
但是,你可以像这样获取你的列表:
SoccerSeasonList seasonList = gson.fromJson(webApiResponse, SoccerSeasonList.class);
ArrayList<SoccerSeason> seasonArr = seasonList.getSeasonList();
并执行如下操作:
for(SoccerSeason ss : seasonArr)
System.out.println(ss.getNumberOfMatchdays());
回顾一下:您只需将 JSON 对象名称和文字与类中的等效 java 类型进行匹配,然后对包含从您想要解析的 Web API 接收到的 JSON 的字符串调用 fromJSON,传入您希望将对象解析到的类。
关于java - 将 JSON 从 WebResource 解析为可用的 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35737203/