fuLLMetaLMan
fuLLMetaLMan

Reputation: 165

Spring restful webservice returning JSON

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

Answers (2)

Nikola Yovchev
Nikola Yovchev

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

mikea
mikea

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

Related Questions