簡體   English   中英

創建Java Spring Boot端點以獲取對象列表作為json

[英]Creating Java Spring Boot endpoint to obtain list of objects as json

我正在嘗試創建一個端點,該端點將對象列表作為JSON返回。

當前的對象結構如下:

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

具有4個屬性的單位列表,其中一個是具有2個屬性的對象的另一個列表。 這是我想要獲得的結果。

我目前正在嘗試在UnitController執行以下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屬性。

這可能是因為控制器上沒有@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(){..}
}

對於以上示例:

  • GET請求發送到/ units將導致對method1調用
  • POST請求發送到/ units將導致對method2調用
  • 向/ units / unit發送GET請求將導致對method3調用

如果您的application.properties文件定義了server.contextPath屬性,則需要將其附加到基本URL,例如<host>:<port>/<contextPath>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM