我正在使用巨型炸彈API製作web應用程序。如何從這樣的JSON中返回列表<Object>?
我被卡住了,因爲我需要從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的,因爲有限制的領域開始一些數據,偏移等)
- 對象映射器(Unirest /傑克遜) - 問題因爲我得到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"
}
]
}
我有遊戲類類似的解決方案,我顯示列表,名爲遊戲。
private List<Game> games = new ArrayList<>();
public List<Game> getAllGames(){
return games;
}
我使用GET請求填充此列表,我輸入id和標題。
來自巨人炸彈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(); }
下本地主機展望:8080 /搜索應該返回對象的列表,從JSON請求獲得的搜索結果。它應該看起來就像localhost:8080/games,它讓我回到我在Postman上使用GET發送的遊戲列表。我知道我從API中獲得了「resource_type」字段,並且沒有「id」字段,但是這對於以後來說是一個問題,因爲我認爲填充選定的類字段並增量添加id不會帶來太大的問題。
https://stackoverflow.com/questions/17037340/converting-jsonarray-to-arraylist –
這是一個ArrayList的(我越來越不兼容的錯誤類型),我不知道如何轉換請求(httpResponse <對象/ JsonNode /字符串>爲例如JSONArray。 –
VapeKop
字符串到JsonArray https://stackoverflow.com/questions/15609306/convert-string-to-json-array –