java - 创建 Java Spring Boot 端点以获取 json 形式的对象列表

标签 java json spring-boot endpoint

我正在尝试创建一个端点,该端点以 JSON 形式返回对象列表。

当前对象结构如下:

units: [
        {
         id: #,
         order: #,
         name: ""
         concepts: [
                    {
                     id: #
                     name: ""
                    },
                    ...
         ]
        },
        ...
]

具有 4 个属性的单位列表,其中一个是具有 2 个其他属性的对象的另一个列表。这就是我想要获得的结果。

我目前正在尝试在我的 UnitController 中执行以下操作:

@RequestMapping(method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
public @ResponseBody List<Unit> getUnits() {
    return unitService.findAll();
}

但是每当我运行应用程序并尝试 curl localhost:8080/units 时,我什么也得不到。这可能是因为我在 Controller 中使用了另一种方法,例如:

@RequestMapping("")
public String index(Map<String, Object> model) {
    List<Unit> units = unitService.findAll();
    model.put("units", units);
    return "units/index";
}

有人可以帮助我解决这个问题并告诉我我做错了什么吗?我真的很感激。

编辑

好的,我将注释移到了类的顶部

@Controller
@RequestMapping(value = "/units", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
public class UnitController extends BaseController {
...
}

并尝试了这样的端点:

@RequestMapping(method = RequestMethod.GET, value = "/units.json")
public @ResponseBody List<Unit> getUnits() {
    return unitService.findAll();
}

但它 curl localhost:8080/units.json 仍然没有给我任何回应。

还忘了提及我的 application.properties 文件没有 server.contextPath 属性。

最佳答案

这可能是因为没有 @RequestMapping Controller 上的注释。 Spring Boot 需要映射来确定当 REST 时需要调用哪个方法。 API 请求已发送。例如。您需要 UnitController 上的以下信息类:

@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/units")
public class UnitController {

如果您的 Controller 类已经具有该方法,那么您需要为方法定义另一个映射,指定请求方法和可选的映射。例如

@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/units")
public class UnitController {

   @RequestMapping(method = RequestMethod.GET)
   public List<Unit> method1(){..}

   @RequestMapping(method = RequestMethod.POST)
   public List<Unit> method2(){..}

   @RequestMapping(method = RequestMethod.GET, value = "/unit")
   public List<Unit> method3(){..}
}

对于上面的例子:

  • 发送 GET对/units 的请求将导致调用 method1
  • 发送 POST对/units 的请求将导致调用 method2
  • 发送 GET对/units/unit 的请求将导致调用 method3

如果您的application.properties文件有 server.contextPath定义属性,然后需要将其附加到 baseurl,例如<host>:<port>/<contextPath>

关于java - 创建 Java Spring Boot 端点以获取 json 形式的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41989832/

相关文章:

c# - 如何使用 C# 将数据库中的所有表所有记录导出为 json

java - spring mvc 如何测试我的服务是否在发布请求中保留实体

java - 无法将 BufferedReader.readLine() 的结果保存到 String

java - SOAP 请求返回 wsdl 而不是预期的 SOAP 响应

javascript - 是否可以将整数作为键存储在 javascript 对象中?

java - 使用 Spring 返回 XML 响应 Rest API

java - JPA:两端都有列表,没有无限循环

java - 在 Docker 中对端点进行 REST 调用

java - 如何最大化 JFrame 的高度?

java - 在 Spring 上下文 : DuplicateFieldException 中使用 XStream 时出错