如何使用RestTemplate在Java中仅解析Web JSON的一部分? [英] How to Parse only a portion of a web JSON in Java using RestTemplate?

查看:65
本文介绍了如何使用RestTemplate在Java中仅解析Web JSON的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此API获取前5篇文章:

I'm trying to get the first 5 articles from this API: https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21

我的代码目前可以完美运行,但是它可以解析NewsAPI的所有10篇文章.

My code works perfectly for now, but it parses all 10 articles of NewsAPI.

代码是:

public News parse() {

    return restTemplate.getForObject
                    ("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21", News.class);

    }
}

结果是:

{
    "totalResults": 10,
    "articles": [
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Measles returns to four European nations, WHO says",
            "url": "http://www.bbc.co.uk/news/health-49507253"
        },
    etc......

当然,我创建了描述Article,Source和News的类.新闻有文章列表.

Of course, i created the classes that describe Article, Source and News. News has a List of Article.

我只想解析前五篇文章并将其保存到列表中.我知道我必须使用For循环,但是我该怎么做?我尝试使用以下代码:

I just want to parse the first five articles and save them into a List. I know I have to use a For cycle, but how can i do that? I tried with this code:

public News parseFive() {
    List<Article> articleList = null;

    for(int i = 0; i<5; i++) {
        articleList = Arrays.asList(
        new Article(restTemplate.getForObject
                                ("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21", Article.class)));
    }
    News news = new News();
    news.setArticles(articleList);
    return news;
}

新闻课是:

public class News {

    private int totalResults;

    private List<Article> articles;

    public News() {

    }

    public int getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(int totalResults) {
        this.totalResults = totalResults;
    }

    public List<Article> getArticles() {
        return articles;
    }

    public void setArticles() {
        this.articles = articles;
    }
}

结果是:

{
    "totalResults": 0,
    "articles": [
        {
            "source": null,
            "author": null,
            "title": null,
            "url": null
        }
    ]
}

问题出在哪里?也许是因为发现的头等舱不是文章而是新闻?谢谢大家的努力.

Where is the problem? Maybe because the first class who finds is not Article but is News? Thanks everyone for the effort.

推荐答案

在使用RestTemplate.getForObject时,从技术上讲,您正在解析整个响应:Spring读取所有字节并使用JSON解析器(Jackson)创建对象.您的for循环(稍后介绍)仅过滤掉5号以后的元素.如果您只想解析前5篇文章,则应考虑使用 Jackson Streaming API .与RestTemplate一起使用时出现问题是安静的,请阅读此答案以获取更多信息.

When you are using RestTemplate.getForObject you are technically parsing the whole response: Spring reads all the bytes and uses JSON parser (Jackson) to create an object. Your for loop, which is covered later, only filters out elements past 5th. If you really want to parse only first 5 articles, you should consider using Jackson Streaming API. It is quiet problematically to use with RestTemplate, read this answer for more info.

现在让我们尝试修复您的parseFive.

Now let's try to fix your parseFive.

首先,创建一个类来捕获整个响应:

First, create a class to capture whole response:

public class Response {
    private String status;
    private Integer totalResults;
    private List<Artice> articles;

    // Getters & Setters
}

现在,获得前五篇文章:

Now, get first five articles:

public News parseFive() {
    final Response response = restTemplate
        .getForObject("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21", Response.class);
    final News news = new News();

    news.setArticles(response.articles.stream().limit(5).collect(Collectors.toList());

    return news;
}

您尚未提供您的News类,可能与响应相同.然后,代码可能如下所示:

You have not provided your News class, probably it is the same as response. Then, the code may look like:

public News parseFive() {
    final News news = restTemplate
        .getForObject("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21", Response.class);

    news.setArticles(news.articles.stream().limit(5).collect(Collectors.toList());

    return news;
}

这篇关于如何使用RestTemplate在Java中仅解析Web JSON的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆