简体   繁体   中英

returning multiple different objects in @RestController method

I am currently working with Spring Rest Web Services and I have set up a @RestController with some methods that each have a @RequestMapping. The problem is that each method can of course only return objects of one type. However, for each request, I might want to return an instance of Class A, one property of Class B and a List containing objects of Class C. Of course, I could make multiple requests, but is there a way we can return multiple different objects with one request?

For further information: I would like to send the objects back to a mobile client in XML format.

You can make your method to return 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;
}

You can return a JsonNode

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

The Jackson converter know how to transform the JsonNode into plain Json.

Or you can tell Spring that your method produces json produces="application/json"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM