【问题标题】:How to properly send a JSON array with Spring api?如何使用 Spring api 正确发送 JSON 数组?
【发布时间】:2019-10-24 16:01:31
【问题描述】:

所以我正在建立一个 lil 网站,该网站应该展示昆虫和一些关于它们的信息,我已经接到了 fetch 调用,并且网站本身已经启动并运行,没问题。在后端,我有一个带有 Spring Boot 的 API,它可以检索我的 InsectObject,它现在只包含一个 titledescription 字符串,并且工作正常。

现在,请原谅我试图尽我所能解释这个问题。

我的问题是我的 API 收到如下响应:

[
    {
        "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 调用应该是这样的。但话又说回来,这是我第一次冒险进入这个领域,我只是按照教程和文档,一路构建我自己的图景。

如果有任何相关性,我的休息控制器如下所示:

@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();
    }
}

我错过了什么?我应该更改 getAll() 方法中的某些内容以获得所需的结果吗?还是无论如何我都应该能够处理第一个结果?我应该返回 List 以外的东西吗?我尝试使用 ResponseEntity,但结果完全相同,只是更冗长。

提前致谢。

【问题讨论】:

  • 您可以为如下响应创建一个类包装器:class BugResponse { private List&lt;InsectObject&gt; bugs; getters/setters .. } 并将其用作BugSiteController.getAll() 的返回

标签: java json ajax spring-boot fetch


【解决方案1】:

您可以在 Model 中设置值,也可以在 Map 中设置它。

型号

class InsectResponse {

  @JsonProperty("bug")
  private List<InsectObject> insectObject;
  // Getter, Setter & Constructor
}

控制器

@GetMapping("/bugs")
public ReponseEntity getAll() { 
   return ResponseEntity.ok(new InsectResponse(repository.findAll()));
}

@GetMapping("/bugs")
public ReponseEntity getAll() { 
   return ResponseEntity.ok(new HashMap<String, List<InsectObject>>() {{
            put("bug", repository.findAll());
        }});
}

【讨论】:

  • 谢谢,使用 Map 可以完美运行,而且实现起来的东西更少(我喜欢保持我的代码很小)。请问 ResponseEntity.ok() 方法中发生了什么?我没有遇到双 {{}}} 括号,我不明白为什么 put() 方法在那里并且功能齐全。
  • 我已经匿名初始化了 Map,而不是创建对象并调用 put 方法。您可以查看javatutorial.net/java-hashmap-inline-initialization,它会让您清楚了解
【解决方案2】:

InsectObject实体类上添加:

@JsonRootName(value = "bug")

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2017-12-04
    • 2017-04-07
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多