将WebResource中的JSON解析为可用的Java对象

时间:2016-03-02 02:15:58

标签: java json jersey

我尝试使用一些web 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 output = response.getEntity(SoccerSeason.class);我有一个经典的com.sun.jersey.api.client.ClientHandlerException 请问我的代码中缺少什么?你知道如何做到这一点吗?

1 个答案:

答案 0 :(得分:2)

你想要的是谷歌的GSON。它可以通过快速谷歌搜索找到,它有大量易于阅读的文档。

将GSON添加到项目依赖项/源代码中,将所有类成员的getter和setter添加到您创建的类中,它应该可以很好地工作。

它的用法如下:

subprocess.check_output([command]) //returns immediately
subprocess.check_output([command, "-i"]) // takes longer to run, returns output
subprocess.call([command]) // also takes longer to run

其中Gson gson = new Gson(); SoccerSeason newSoccerSeason = gson.fromJson(webApiResponse, SoccerSeason.class); String lastUpdated = newSoccerSeason.getLastUpdated(); 是作为Web API响应收到的JSON的String表示形式。您还可以定义类webApiResponse,如下所示:

SoccerSeasonList

当然,您传入的JSON必须有一个名为seasonList的对象,其中包含您的所有public class SoccerSeasonList { ArrayList<SoccerSeason> seasonList; // getters/setters } 个对象以匹配此定义。

但是,你可以像这样抓住你的名单:

SoccerSeason

执行如下操作:

SoccerSeasonList seasonList = gson.fromJson(webApiResponse, SoccerSeasonList.class);
ArrayList<SoccerSeason> seasonArr = seasonList.getSeasonList();

回顾一下:您只需将JSON对象名称和文字与类中的等效java类型相匹配,并在包含从您要解析的Web API接收的JSON的String上调用fromJSON,并传入你想要解析对象的类。