2

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.

2
  • 1
    At a minimum, provide a concrete example. It sounds like this is an abstract what-if that would resolve if reduced to specifics. Commented Dec 8, 2015 at 21:36
  • dont know java spring but maybe : return object / return base class / return generic / return json string / ... Commented Dec 8, 2015 at 21:40

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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\"}";
}

1 Comment

Yes you can use MediaType.APPLICATION_XML_VALUE instead of MediaType.APPLICATION_JSON_VALUE in the produces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.