【发布时间】:2017-12-18 03:12:22
【问题描述】:
我正在使用 Giant Bomb API 制作网络应用。
我被卡住了,因为我需要从 GET 请求(使用 Unirest)获取搜索结果列表,然后方便地将其转换为称为建议的对象列表。
这就是我的问题所在:
private List<Suggestion> suggestions = new ArrayList<>();
public List<Suggestion> searchGames(){
HttpResponse<String> request;
try {
request = Unirest.get("http://giantbomb.com/api/search/?api_key=xxxxxxxxxxxxxxxxxxxxxxxxx&format=json&resources=game&limit=10&field_list=name&query=creed")
.header("Accept", "application/json")
.asString();
String requestString = request.toString(); //I can get my request as String, but that doesnt change much, I guess
//>>> the problematic part <<<
return suggestions;
}
我缺少一些可以让我将 JSON 响应从 Unirest 转换为列表的东西。这是我尝试过的:
- GSON - JSON 格式问题(JSON 开头有一些数据,因为有 Limit、Offset 等字段)
- Object Mapper (Unirest/Jackson) - 问题因为我得到的是 httpResponse 而不是 String/Object/JsonNode 等。
- 使用 JSONObject、JSONArray 和 for 循环 - 也没有运气。
我来自 Unirest 调用的 JSON 看起来很像这样:
{
"error": "OK",
"limit": 10,
"offset": 0,
"number_of_page_results": 1,
"number_of_total_results": 3,
"status_code": 1,
"results": [
{
"name": "Assassin's Creed",
"resource_type": "game"
},
{
"name": "The Creed",
"resource_type": "game"
},
{
"name": "Assassin's Creed: Lost Legacy",
"resource_type": "game"
}
]
}
我有一个类似的 Game 类解决方案,我在其中显示名为游戏的列表。
private List<Game> games = new ArrayList<>();
public List<Game> getAllGames(){
return games;
}
我使用输入 id 和标题的 GET 请求填充此列表。
来自 Giant Bomb API 的建议对我来说比较棘手,因为我使用外部 API 来获取对象列表,而不是输入我的输入数据。
我的 Suggestion.java 类如下所示:
package rest.library;
public class Suggestion {
private long id;
private String name;
public Suggestion(){
}
public Suggestion(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}
在我的控制器中我想这样做:
@RequestMapping("/search")
public List<Suggestion> searchGames() { return gameService.searchGames(); }
在 localhost:8080/search 下应该返回一个对象列表,其中包含从 JSON 请求获得的搜索结果。它应该看起来就像 localhost:8080/games 一样,它会返回我在 Postman 上使用 GET 发送的游戏列表。我知道我从 API 获得了字段“resource_type”并且没有“id”字段,但这是以后的问题,因为我认为填充选定的类字段并逐步添加 id 不会有那么大的问题。
【问题讨论】:
-
这是针对 ArrayList
的(我遇到类型不兼容的错误),我不知道如何将请求(httpResponse -
字符串到 JsonArray stackoverflow.com/questions/15609306/…
-
JSONObject myObject = new JSONObject(result);