我正在尝试创建一个端点,该端点以 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/