Java 如何使用SpringAPI正确发送JSON数组?
所以我正在建立一个lil网站,该网站应该展示昆虫和一些关于它们的信息,我已经接到了取回电话,网站本身也开始运行了,没问题。在后端,我有一个带有Spring引导的API,用于检索我的InsteToObject,目前它只保存一个标题和描述字符串,工作正常 现在,请原谅,我正在尽力解释这个问题 我的问题是,我从API中得到如下响应:Java 如何使用SpringAPI正确发送JSON数组?,java,json,ajax,spring-boot,fetch,Java,Json,Ajax,Spring Boot,Fetch,所以我正在建立一个lil网站,该网站应该展示昆虫和一些关于它们的信息,我已经接到了取回电话,网站本身也开始运行了,没问题。在后端,我有一个带有Spring引导的API,用于检索我的InsteToObject,目前它只保存一个标题和描述字符串,工作正常 现在,请原谅,我正在尽力解释这个问题 我的问题是,我从API中得到如下响应: [ { "id": 1, "title": "mantis", "description": "leafy boi
[
{
"id": 1,
"title": "mantis",
"description": "leafy boi"
},
{
"id": 2,
"title": "moth",
"description": "fly boi"
}
]
我希望它以以下形式返回:
{
bugs: [
{
"id": 1,
"title": "mantis",
"description": "leafy boi"
},
{
"id": 2,
"title": "moth",
"description": "fly boi"
}
]
}
我认为正确的api调用应该是这样的。但话说回来,这是我第一次冒险进入这个领域,我只是遵循教程和文档,一路上构建自己的图片
如果与此相关,我的rest控制器如下所示:
@RestController
public class BugSiteController {
private final InsectRepository repository;
BugSiteController(InsectRepository repository) {
this.repository = repository;
}
// get all bugs from the repo
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/bugs")
List<InsectObject> getAll() {
return repository.findAll();
}
}
@RestController
公共类BugSiteController{
私人最终昆虫储存库;
BugSiteController(昆虫存储库){
this.repository=存储库;
}
//从回购协议中获取所有bug
@交叉原点(原点=”http://localhost:3000")
@GetMapping(“/bugs”)
List getAll(){
返回repository.findAll();
}
}
我错过了什么?在我的getAll()方法中,是否应该更改某些内容以获得所需的结果?或者我应该能够处理第一个结果吗?我是否应该返回列表以外的内容?我试着回应,但结果完全一样,只是更加冗长
提前感谢。关于
insteToObject
实体类添加:
@JsonRootName(value = "bug")
在
insteToObject
实体类中添加:
@JsonRootName(value = "bug")
您可以在模型中设置值,也可以在地图中设置值 模型
类不安全响应{
@JsonProperty(“bug”)
私有列表对象;
//Getter、Setter和Constructor
}
控制器
@GetMapping(“/bugs”)
public ReponseEntity getAll(){
返回ResponseEntity.ok(新的昆虫响应(repository.findAll());
}
或
@GetMapping(“/bugs”)
public ReponseEntity getAll(){
返回ResponseEntity.ok(新的HashMap(){{
put(“bug”,repository.findAll());
}});
}
您可以在模型中设置值,也可以在地图中设置值
模型
类不安全响应{
@JsonProperty(“bug”)
私有列表对象;
//Getter、Setter和Constructor
}
控制器
@GetMapping(“/bugs”)
public ReponseEntity getAll(){
返回ResponseEntity.ok(新的昆虫响应(repository.findAll());
}
或
@GetMapping(“/bugs”)
public ReponseEntity getAll(){
返回ResponseEntity.ok(新的HashMap(){{
put(“bug”,repository.findAll());
}});
}
您可以为如下响应创建类包装:类BugResponse{private List bugs;getter/setters..}
并将其用作BugSiteController.getAll()的返回。
您可以为响应创建类包装,如:类BugResponse{private List bugs;getter/setters..}
并将其用作返回BugSiteController.getAll()
谢谢,使用映射非常有效,而且实现起来也比较简单(我喜欢将代码保持在较小的范围内)。请问ResponseEntity.ok()方法中发生了什么?我没有遇到双{{}}方括号,我也不明白为什么put()方法在那里并且功能齐全。我以匿名方式初始化了映射,而不是创建对象并调用put方法。你可以检查它,它会让你清楚地了解你,使用一个地图工作得很好,而且它实现的东西更少(我喜欢保持我的代码小)。请问ResponseEntity.ok()方法中发生了什么?我没有遇到双{{}}方括号,我也不明白为什么put()方法在那里并且功能齐全。我以匿名方式初始化了映射,而不是创建对象并调用put方法。你可以检查一下,它会给你清晰的理解