创建JavaSpring引导端点以获取json形式的对象列表

创建JavaSpring引导端点以获取json形式的对象列表,java,json,spring-boot,endpoint,Java,Json,Spring Boot,Endpoint,我正在尝试创建一个端点,它以JSON的形式返回对象列表 当前对象结构如下所示: units: [ { id: #, order: #, name: "" concepts: [ { id: # name: "" },

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

当前对象结构如下所示:

units: [
        {
         id: #,
         order: #,
         name: ""
         concepts: [
                    {
                     id: #
                     name: ""
                    },
                    ...
         ]
        },
        ...
]
具有4个属性的单元列表,其中一个是具有2个Other属性的另一个对象列表。这就是我希望得到的结果

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

@RequestMapping(method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
public @ResponseBody List<Unit> getUnits() {
    return unitService.findAll();
}
有人能帮我渡过难关,告诉我我做错了什么吗?我真的很感激

编辑

好的,所以我把注释移到了类的顶部

@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();
}
@RequestMapping(method=RequestMethod.GET,value=“/units.json”)
public@ResponseBody List getUnits(){
return unitService.findAll();
}
但是它仍然没有给我任何响应


还忘了提到我的
应用程序.properties
文件没有
服务器.contextPath
属性。

这可能是因为控制器上没有
@RequestMapping
注释。Spring boot需要映射,以确定在发送
REST
API请求时需要调用哪个方法。例如,您需要在
UnitController
类上执行以下操作:

@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/units")
public class UnitController {
如果您的控制器类已经有了该映射,那么您需要为方法定义另一个映射,指定request method和mapping(可选)。例如

@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(){..}
}
@RestController
@RequestMapping(products=MediaType.APPLICATION\u JSON\u UTF8\u VALUE,VALUE=“/units”)
公共类单元控制器{
@RequestMapping(method=RequestMethod.GET)
公共列表方法1(){..}
@RequestMapping(method=RequestMethod.POST)
公共列表方法2(){..}
@RequestMapping(method=RequestMethod.GET,value=“/unit”)
公共列表方法3(){..}
}
对于上述示例:

  • 向/units发送
    GET
    请求将导致调用
    method1
  • 向/units发送
    POST
    请求将导致调用
    method2
  • 向/units/units发送
    GET
    请求将导致调用
    method3
如果您的
应用程序.properties
文件定义了
服务器.contextPath
属性,则需要将其附加到baseurl,例如
:/

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