簡體   English   中英

在@RestController方法中返回多個不同的對象

[英]returning multiple different objects in @RestController method

我目前正在使用Spring Rest Web Services,並且已經設置了@RestController以及一些每個都有@RequestMapping的方法。 問題在於,每個方法當然只能返回一種類型的對象。 但是,對於每個請求,我可能希望返回一個A類的實例,一個B類的屬性和一個包含C類對象的列表。當然,我可以發出多個請求,但是有一種方法可以返回多個不同的對象。一個請求的對象?

有關更多信息:我想將對象以XML格式發送回移動客戶端。

您可以使您的方法返回Map<String,Object>

@RequestMapping(value = "testMap", method = RequestMethod.GET)
public Map<String,Object> getTestMap() {
    Map<String,Object> map=new HashMap<>();
    //put all the values in the map
    return map;
}

您可以返回一個JsonNode

@RequestMapping(..)
@ResponseBody
public JsonNode myGetRequest(){
...
//rawJsonString is the raw Json that we want to proxy back to the client
return objectMapper.readTree(rawJsonString);
}

Jackson轉換器知道如何將JsonNode轉換為純Json。

或者,您可以告訴Spring您的方法產生json producer =“ application / json”

@RequestMapping(value = "test", method = RequestMethod.GET, produces="application/json")
public @ResponseBody
String getTest() {
    return "{\"a\":1, \"b\":\"foo\"}";
}

暫無
暫無

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

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