如何从这样的JSON返回List <object>?

时间:2017-07-13 11:09:59

标签: java json spring unirest

我正在使用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转换为List的内容。这就是我的尝试:

  • GSON - JSON格式的问题(由于字段包含Limit,Offset等等,JSON开头有一些数据)
  • Object Mapper(Unirest / Jackson) - 因为我得到httpResponse而不是String / Object / JsonNode等问题。
  • 使用JSONObject,JSONArray和for循环 - 也没有运气。

来自Unirest的My 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类的解决方案,我在其中显示名为games的List。

private List<Game> games = new ArrayList<>();

public List<Game> getAllGames(){
    return games;
}

我使用GET请求填充此列表,我输入了id和title。

来自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 /游戏,它返回了我在Postman上使用GET发送的游戏列表。我知道我得到了字段&#34; resource_type&#34;来自API,没有&#34; id&#34;字段,但这是一个问题,因为我认为填充选定的类字段并添加id incrementaly不会成为一个问题。

2 个答案:

答案 0 :(得分:1)

你需要的是一种将你从请求中收到的String对象映射到HashMap的方法,这样你就可以设置你的对象属性,然后形成一个返回的列表(尽管像Jackson这样的API可以实现REST请求处理逻辑不那么痛苦了。)

这意味着首先使用response.getEntity().getContent()从HTTP请求获取InputStream,然后按照here创建JSONParser。

这将使您能够从显示here的JSON字符串中获取属性。

反过来,这将使您能够使用setter方法创建自己的对象列表。

如果有帮助,请告诉我。

答案 1 :(得分:0)

我建议使用基于apache http api构建的http-request。您可以创建类ResponseData来解析响应。

Microsoft.CodeAnalysis.Workspaces.Common
相关问题