Search code examples
javamongodbresttemplate

How To Extract Data From JSON with Rest Template in Java


i have to extract the first 5 articles from https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21, having a result like this:

{
    "total": 5,
    "articles": [
{
    "source": "Ilmessaggero.it",
    "title": "Title",
    "author": "Author",
    "url": "URL"
  }
 ]
}

I did this, having all the JSON as String as output for the localhost...

@RequestMapping("/news")
    public Article connection() {

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

The result in the localhost is:

{"source":null,"title":null,"author":null,"url":null}

But the problem now is, how do i put the data into the list of articles? and how do i save them into mongodb? thanks for the effort


Solution

  • I solved it! SImply, the NewsAPI json of Article has a field called Source, which i was trying to parse as a string, but it was NOT! Infact, it is a field described with another object! I simply had to create a class called Source with id and name, and it works! Thanks everyone for the effort!

    Here's the codes of the classes:

    public class Article {
    
        private Source source;
    
        private String author;
    
        private String title;
    
        private String url;
    
        //getters and setters
    

    News, which has a list of articles:

    public class News {
    
        private int totalResults;
    
        private List<Article> articles;
    
        //getters and setters
    

    And source, which is called in Article:

    public class Source {
    
        private String id;
    
        private String name;
    
        //getters and setters
    

    Here it is! The parse code is the same of the answer. Just change the return type (Article) as News and the Article.class parameter of getForObject into News.class