使用Java调用REST API并解析JSON数据的最简单方法

4

我试图在JavaScript中做一些微不足道的事情,但在Java中似乎很复杂。希望有人能够指出如何在Java中简单地完成它。

我想调用REST JSON API,例如https://images-api.nasa.gov/search?q=clouds

我收到的数据结构,在简化形式下,类似于这样:

{
  "collection": {
    "items": [
      {
        "links": [
          {
            "href": "https://images-assets.nasa.gov/image/cloud-vortices_22531636120_o/cloud-vortices_22531636120_o~thumb.jpg",
            "rel": "preview"
          }
        ]
      }
    ]
  }
}

在Java中,我想调用URL并将href字符串作为列表返回。
在JavaScript中,我会简单地编写
fetch("https://images-api.nasa.gov/search?q=moon")
  .then(data => data.json())
  .then(data => {
    const items = data
      .collection
      .items
      .map(item => item.links)
      .flat()
      .filter(link => link.rel === "preview")
      .map(link => link.href);

    // do something with "items"
})

1. 我的初步解决方案

通过一些搜索,我找到了这种方法,看起来是朝着正确的方向前进,但仍然非常冗长。

String uri = "https://images-api.nasa.gov/search?q=clouds";
List<String> hrefs = new ArrayList<>();

try {
    // make the GET request
    URLConnection request = new URL(uri).openConnection();
    request.connect();
    InputStreamReader inputStreamReader = new InputStreamReader((InputStream) request.getContent());

    // map to GSON objects
    JsonElement root = new JsonParser().parse(inputStreamReader);

    // traverse the JSON data 
    JsonArray items = root
            .getAsJsonObject()
            .get("collection").getAsJsonObject()
            .get("items").getAsJsonArray();

    // flatten nested arrays
    JsonArray links = new JsonArray();
    items.forEach(item -> links.addAll(item
            .getAsJsonObject()
            .get("links")
            .getAsJsonArray()));

    // filter links with "href" properties
    links.forEach(link -> {
        JsonObject linkObject = link.getAsJsonObject();
        String relString = linkObject.get("rel").getAsString();
        if ("preview".equals(relString)) {
            hrefs.add(linkObject.get("href").getAsString());
        }
    });

} catch (IOException e) {
    e.printStackTrace();
}

return hrefs;

我的剩余问题是:

  • 是否有一种方法可以使用RestTemplate或其他库使GET请求更简洁,同时保持GSON的通用灵活性?
  • 是否有一种方法可以展开嵌套的JsonArrays和/或使用GSON过滤JsonArrays,以便我不需要创建额外的临时JsonArrays?
  • 是否还有其他减少冗余代码的方法?

已编辑

在阅读下面的评论和答案后添加了以下部分。


2. 更简洁的解决方案

(如@diutsu所提出的)

List<String> hrefs = new ArrayList<>();
String json = new RestTemplate().getForObject("https://images-api.nasa.gov/search?q=clouds", String.class);
new JsonParser().parse(json).getAsJsonObject()
    .get("collection").getAsJsonObject()
    .get("items").getAsJsonArray()
    .forEach(item -> item.getAsJsonObject()
        .get("links").getAsJsonArray()
        .forEach(link -> {
            JsonObject linkObject = link.getAsJsonObject();
            String relString = linkObject.get("rel").getAsString();
            if ("preview".equals(relString)) {
                hrefs.add(linkObject.get("href").getAsString());
            }
        })
    );
return hrefs;

3. 使用 Mapper POJOs 的解决方案

(受 @JBNizet 和 @diutsu 启发)

现在,实际的 GET 请求和转换只需要一行代码,几乎与我上面提供的 JavaScript 代码相同,...

return new RestTemplate().getForObject("https://images-api.nasa.gov/search?q=clouds", CollectionWrapper.class)
    .getCollection()
    .getItems().stream()
    .map(Item::getLinks)
    .flatMap(List::stream)
    .filter(item -> "preview".equals(item.getRel()))
    .map(Link::getHref)
    .collect(Collectors.toList());

为了实现这个目标,我需要创建以下4个类:

CollectionWrapper

public class CollectionWrapper {

    private Collection collection;

    public CollectionWrapper(){}

    public CollectionWrapper(Collection collection) {
        this.collection = collection;
    }

    public Collection getCollection() {
        return collection;
    }
}

集合

public class Collection {

    private List<Item> items;

    public Collection(){}

    public Collection(List<Item> items) {
        this.items = items;
    }

    public List<Item> getItems() {
        return items;
    }
}

项目

public class Item {

    private List<Link> links;

    public Item(){}

    public Item(List<Link> links) {
        this.links = links;
    }

    public List<Link> getLinks() {
        return links;
    }
}

链接

public class Link {

    private String href;
    private String rel;

    public Link() {}

    public Link(String href, String rel) {
        this.href = href;
        this.rel = rel;
    }

    public String getHref() {
        return href;
    }

    public String getRel() {
        return rel;
    }
}

4. 使用 Kotlin

(受 @NBNizet 启发)

val collectionWrapper = RestTemplate().getForObject("https://images-api.nasa.gov/search?q=clouds", CollectionWrapper::class.java);
return collectionWrapper
        ?.collection
        ?.items
        ?.map { item -> item.links }
        ?.flatten()
        ?.filter { item -> "preview".equals(item.rel) }
        ?.map { item -> item.href }
        .orEmpty()

使用Kotlin可以使映射器类更简单,甚至比使用Java和Lombok还要简单。

data class CollectionWrapper(val collection: Collection)
data class Collection(val items: List<Item>)
data class Item(val links: List<Link>)
data class Link(val rel: String, val href: String)

5. 直接映射到Map和List

我不确定这是否是一个好主意,但知道可以这样做:

return 
    ( (Map<String, Map<String, List<Map<String, List<Map<String, String>>>>>>) 
        new RestTemplate()
        .getForObject("https://images-api.nasa.gov/search?q=clouds", Map.class)
    )
    .get("collection")
    .get("items").stream()
    .map(item -> item.get("links"))
    .flatMap(List::stream)
    .filter(link -> "preview".equals(link.get("rel")))
    .map(link -> link.get("href"))
    .collect(Collectors.toList());

1
无论使用哪个HTTP客户端库,我通常更喜欢让JSON映射器(通常是Jackson或Gson)将JSON映射到自定义的Java类中,使用标准集合和类型化和命名属性。 - JB Nizet
@JBNizet 我理解这个想法,但是对我来说,为了访问上面示例中所需的数据,这似乎需要做很多工作,不是吗?在创建整个模型类结构之前,您甚至无法进行GET请求,这在本例中意味着至少要创建ItemsList、Item、LinkList和Link等类,每个类都有它们自己的构造函数和getter、注释以及toString()、hashCode()和equals()方法。这就是你所指的吗? - Chris
1
是的,Java不是动态语言,因此您可以使用JSONArray/JSONObject、Maps和Lists或实际的Java对象。我使用Kotlin,它使创建这些POJO更简单、更简洁。但话说回来,这些POJOs不需要hashCode/equals/toString,也不需要注释。 - JB Nizet
2
你不需要为每个类定义注释、toString、hashCode和equals。此外,看一下lombook,它会有所帮助。 - diutsu
1个回答

2

1) 转换为字符串

restTemplate.getForObject("https://images-api.nasa.gov/search?q=clouds", String.class)

2) 简单点,不要使用数组。 我会说这样做会让代码可读性降低,但你可以提取一些方法来帮助解决这个问题。

root.getAsJsonObject()
    .get("collection").getAsJsonObject()
    .get("items").getAsJsonArray()
    .forEach(item -> item.getAsJsonObject()
       .get("links").getAsJsonArray()
       .forEach(link -> {
            JsonObject linkObject = link.getAsJsonObject();
            String relString = linkObject.get("rel").getAsString();
            if ("preview".equals(relString)) {
               hrefs.add(linkObject.get("href").getAsString());
            }));

3) 如果你想保持简单,那就不需要这么做 :D 你可以定义自己的结构,然后直接从restTemplate获取到该结构。这只需要一行代码。但是由于你只关心hrefs,所以这样做没有意义。

最初的回答:

如果您希望保持简单,您可以定义自己的结构,然后直接从restTemplate获取该结构。这只需要一行代码。但是,由于您只关心hrefs,因此这种方法没有意义。


这太完美了。谢谢你。我会用这个建议来更新我的解决方案。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接