![](/img/trans.png)
[英]How to implement API returns nested JSON with OneToMany relationship in Spring Boot?
[英]How to mock an api that returns a json string in spring boot
我是尝试在 Spring Boot 中模拟外部 api 的初学者。 这是 API: https : //jsonplaceholder.typicode.com/posts
它返回一个 json 字符串,如下所示:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
...
我试过以下代码:
@Service
public class BlogPostService {
@Autowired
private RestTemplate restTemplate;
public String getAllBlogPosts() {
ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/posts", String.class);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
}
But there is an error in the IDE at resp.getBody() which says
类型不匹配:无法从对象转换为字符串
这是我的博客帖子代码:
public class BlogPost {
private int userId;
private String title;
private String body;
public BlogPost() {
}
public BlogPost(int userId, String title, String body) {
this.title = title;
this.body = body;
}
//...getters & setters
你们中的一位专家能给我一些指导吗? 希望不使用另一种工具。 这只是一个简单的概念验证应用程序,因此不想使用 JUnit 或 Mockito 进行测试。
API https://jsonplaceholder.typicode.com/posts
返回一个 JSON 对象数组。 您需要在请求所需的响应类型中反映这一点
public String getAllBlogPosts() {
ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/posts", BlogPost[].class);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
注意到[]
在BlogPost[].class
。
然后,您遇到Type mismatch: cannot convert from Object to String
因为ResponseBody.getBody()
返回泛型类型T
,即BlogPost[]
但您的方法签名返回String
。
如果你想要的只是 JSON 字符串,那么你可以这样做
public String getAllBlogPosts() {
ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/posts", String.class);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
否则,如果您想要实际的 POJO 数组,请执行此操作
public BlogPost[] getAllBlogPosts() {
ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/posts", BlogPost[].class);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.