【问题标题】:Creating Java Spring Boot endpoint to obtain list of objects as json创建 Java Spring Boot 端点以获取对象列表为 json
【发布时间】:2017-02-01 21:12:06
【问题描述】:

我正在尝试创建一个以 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 时,我什么都得不到。这可能是因为我在控制器中有另一种方法,比如这个:

@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 属性。

【问题讨论】:

    标签: java json spring-boot endpoint


    【解决方案1】:

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

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

    如果你的控制器类已经有这个,那么你需要为方法定义另一个映射,指定请求方法和可选的映射。例如

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

    对于上面的例子:

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

    如果您的 application.properties 文件定义了 server.contextPath 属性,则需要将其附加到 baseurl,例如&lt;host&gt;:&lt;port&gt;/&lt;contextPath&gt;

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 2021-07-16
      • 1970-01-01
      • 2015-05-07
      • 2020-03-03
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      相关资源
      最近更新 更多