Java Spring restful Web服务返回JSON
我刚刚在Spring.io上接受了教程,并创建了一个简单的rest服务。但是,有人知道如何以JSON格式返回多个对象吗?例如,如果我有一个带有名称和id的person类,如何向/persons添加三个人?尝试从方法返回列表:Java Spring restful Web服务返回JSON,java,json,spring,rest,Java,Json,Spring,Rest,我刚刚在Spring.io上接受了教程,并创建了一个简单的rest服务。但是,有人知道如何以JSON格式返回多个对象吗?例如,如果我有一个带有名称和id的person类,如何向/persons添加三个人?尝试从方法返回列表: @RequestMapping("/greetings") public @ResponseBody List<Greeting> greetings( @RequestParam(value="name", required=false, de
@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)));
}
@RequestMapping(“/greetings”)
public@ResponseBody列表问候语(
@RequestParam(value=“name”,required=false,defaultValue=“World”)字符串名){
返回Arrays.asList(新的问候语(counter.incrementAndGet(),String.format(template,name));
}
您可以使用@ResponseBody
注释,只要返回您想要的任何内容,前提是这些对象可以被JSONIZE化
例如,您可以有这样一个bean:
@Data
public class SomePojo {
private String someProp;
private List<String> someListOfProps;
}
同样,您可以绑定到一些对象,但这次使用@RequestBody
注释,jackson这次将用于为您预转换json
你能做的就是
@RequestMapping("/someOtherRequestMapping")
public void doStuff(@RequestBody List<SomePojo> somePojos) {
//do stuff with the pojos
}
@RequestMapping(“/someOtherRequestMapping”)
公共void doStuff(@RequestBody List somePojos){
//用pojo做点什么
}
非常酷!我对Spring和其他所有的想法都很陌生。你知道这方面有什么好的教程吗?我需要得到一个类似这样的json:[{“id”:0,“name”:“Sancho Panza”},{“id”:1,“name”:“Man Mansen”},{“id”:2,“name”:“Heman matt”}]然后列出这些人并返回:)呵呵,是的。我有点不确定,因为当我尝试时,它不起作用。但现在确实如此。小语法错误。谢谢你!工作就像一个符咒:D
[{"someProp":"someProp", "someListOfProps": ["prop1", "prop2"]}]
@RequestMapping("/someOtherRequestMapping")
public void doStuff(@RequestBody List<SomePojo> somePojos) {
//do stuff with the pojos
}