繁体   English   中英

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

[英]Simplest way to call REST API and parse JSON data with Java

我正在尝试在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 Request不再那么冗长,并且仍然保持GSON的通用灵活性?
  • 有没有一种方法可以使用GSON展平嵌套的JsonArrays和/或过滤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 POJO的解决方案

(由@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.直接映射到地图和列表

我不认为这是一个好主意,但很高兴知道可以做到这一点:

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)获取字符串

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,所以没有任何意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM