如何使用REST Api,然后将热门故事显示为JSON

时间:2019-05-19 19:56:37

标签: java json rest spring-boot

目标:创建一个Spring Boot项目以使用NY Times的公共API来显示当前的热门新闻。

我所做的事情:我已经使用了REST Api,并将响应存储到jsonObject中。我已经尝试通过两个单元测试,但是无法通过第一个junit测试。即使我通过了第二次junit测试,也可以肯定我的操作是不正确的。

新闻POJO

public class News {

private String title;
private String section;

// GETTER & SETTER

}

新闻服务类

@Service public class NewsService {

private String apiKey = "gIIWu7P82GBslJAd0MUSbKMrOaqHjWOo";

public News getTopStories() throws Exception {


    RestTemplate restTemplate = new RestTemplate();
    News news = new News();

    String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=" + apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
    JSONObject jsonObject;

    if (newsList.getStatusCode() == HttpStatus.OK) {

        jsonObject = new JSONObject(newsList.getBody());
        JSONArray jsonArray = jsonObject.getJSONArray("results");

        for(int i=0; i<jsonArray.length(); i++) {

            news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
            news.setSection(jsonArray.getJSONObject(i).get("section").toString());

        }
    }
    // this is only returning the last index of the jsonArray (pretty sure I am suppose to return all to in my URL). Can't seem to come up with the logic to do that.
    return news; 
}

}

新闻管理员类别

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class NewsController {

@Autowired
NewsService newsService;

@RequestMapping(value = "/news/topstories", method = RequestMethod.GET)
public News getNews() throws Exception {
    return newsService.getTopStories();
}

}

需要通过的JUnit测试

@Test
public void retrievetest_ok() throws Exception {

     mockMvc.perform(get("/api/news/topstories" )).andDo(print())
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.results.[0].title").exists())
                .andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());


}

@Test public void Newstest_ok() throws Exception {
    mockMvc.perform(get("/api/news/topstories" ))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.title").exists())
            .andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
}


}

我在第一次JUnit测试中收到的错误

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /api/news/topstories
   Parameters = {}
      Headers = {}

Handler:
         Type = com.example.project.NewsController
       Method = public com.example.project.News com.example.project.NewsController.getNews() throws java.lang.Exception

Async:
  Async started = false
  Async result = null

Resolved Exception:
         Type = null

ModelAndView:
    View name = null
         View = null
        Model = null

FlashMap:
   Attributes = null


 MockHttpServletResponse:
       Status = 200
 Error message = null
      Headers = {Content-Type=[application/json;charset=UTF-8]}
 Content type = application/json;charset=UTF-8
         Body = {"title":"Shrinking and Quaking Hint at Moon’s Tectonic Life","section":"Science"}
Forwarded URL = null
Redirected URL = null
      Cookies = []

java.lang.AssertionError: No value at JSON path "$.results.[0].title", exception: Missing property in path $['results']
...
...
...
...

3 个答案:

答案 0 :(得分:1)

您应该为每个热门故事创建一个新对象

public List<News> getTopStories() throws Exception {

    List<News> topStories = new ArrayList<>();
    RestTemplate restTemplate = new RestTemplate();

    String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=" + apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
    JSONObject jsonObject;

    if (newsList.getStatusCode() == HttpStatus.OK) {

        jsonObject = new JSONObject(newsList.getBody());
        JSONArray jsonArray = jsonObject.getJSONArray("results");

        for(int i=0; i<jsonArray.length(); i++) {
            News news = new News();
            news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
            news.setSection(jsonArray.getJSONObject(i).get("section").toString());
            topStories.add(news);
        }
    }
    // this is only returning the last index of the jsonArray (pretty sure I am suppose to return all to in my URL). Can't seem to come up with the logic to do that.
    return topStories; 
}

还应调整您的控制器和测试以处理列表结果。

答案 1 :(得分:1)

POJO需要更新以通过所有测试用例。

public class News{
    private String section;
    private Results[] results;
    private String title;


    public Results[] getResults() {
        return results;
    }

    public void setResults(Results[] results) {
        this.results = results;
    }

    public String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

然后您需要再添加一个称为Result的POJO类

public class Results{
    private String title;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}

最后是服务类

public News getTopStories()
    {
        List<News> topStories = new ArrayList<>();
        RestTemplate restTemplate = new RestTemplate();
        String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=<your-api-key>";
        News news=new News();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
        JSONObject jsonObject;

        if (newsList.getStatusCode() == HttpStatus.OK) {

            jsonObject = new JSONObject(newsList.getBody());
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            Results[] results = new Results[jsonArray.length()];
            for(int i=0; i<jsonArray.length(); i++) {
                news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
                news.setSection(jsonArray.getJSONObject(i).get("section").toString());
                String title=jsonArray.getJSONObject(i).get("title").toString();
                results[i]=new Results();
                results[i].setTitle(title);
                news.setResults(results);
                topStories.add(news);
            }

        }
        return topStories.get(0); 
    }

这对于您提到的所有JUnit肯定有效。 或者甚至可以创建内部类Result而不是创建新的POJO文件。

答案 2 :(得分:1)

对于特定的测试,您需要在 News.java 本身中创建一个结果类。

import java.util.List;

class Results{
    private String title;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}


public class News {
private String title;
private String section;
private Results[] results;

public Results[] getResults() {
        return results;
    }

    public void setResults(Results[] results) {
        this.results = results;
    }

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getSection() {
    return section;
}
public void setSection(String section) {
    this.section = section;
}

}

然后在您的新闻服务类

@Service
public class NewsService {

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   return builder.build();
}

@Autowired
private RestTemplate restTemplate;

private String apiKey = "<---Your_Key--->";

    public News getTopStories() {
     List<News> topStories = new ArrayList<>();

    String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=" + apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
    JSONObject jsonObject;

    if (newsList.getStatusCode() == HttpStatus.OK) {

        jsonObject = new JSONObject(newsList.getBody());
        JSONArray jsonArray = jsonObject.getJSONArray("results");
        Results[] results = new Results[jsonArray.length()];

        for(int i=0; i<jsonArray.length(); i++) {
            News news = new News();
            news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
            news.setSection(jsonArray.getJSONObject(i).get("section").toString());
            String title=jsonArray.getJSONObject(i).get("title").toString();
            results[i]=new Results();
            results[i].setTitle(title);
            news.setResults(results);
            topStories.add(news);
        }
    }
    return topStories.get(0);
  }
}