Reputation: 165
I just took the tutorial over at Spring.io http://spring.io/guides/gs/rest-service/ and created a simple rest service. But, does anybody know how I can return multiple objects in JSON format? If I for instance have a person class with a name and an id, how can I add three persons to /persons?
Upvotes: 2
Views: 2434
Reputation: 10276
You can use the @ResponseBody
annotation and just return whatever you want, providing that those objects can be jsonized.
For example, you can have a bean like this:
@Data
public class SomePojo {
private String someProp;
private List<String> someListOfProps;
}
and then in your controller you can have:
@ResponseBody
@RequestMapping("/someRequestMapping")
public List<SomePojo> getSomePojos(){
return Arrays.<String>asList(new SomePojo("someProp", Arrays.<String>asList("prop1", "prop2"));
}
and Spring by default would use its Jackson mapper to do it, so you'd get a response like:
[{"someProp":"someProp", "someListOfProps": ["prop1", "prop2"]}]
The same way, you can bind to some objects, but this time, using the @RequestBody
annotation, where jackson would be used this time to pre-convert the json for you.
what you can do is
@RequestMapping("/someOtherRequestMapping")
public void doStuff(@RequestBody List<SomePojo> somePojos) {
//do stuff with the pojos
}
Upvotes: 8
Reputation: 6667
Try returning a list from the method:
@RequestMapping("/greetings")
public @ResponseBody List<Greeting> greetings(
@RequestParam(value="name", required=false, defaultValue="World") String name) {
return Arrays.asList(new Greeting(counter.incrementAndGet(),String.format(template, name)));
}
Upvotes: 1