How to return a set of objects with Spring Boot?

后端 未结 3 1362
情书的邮戳
情书的邮戳 2020-12-09 05:52

I did a lesson about Spring Boot and it works perfectly. But what if I want to return a set of objects ? I tried doing this but it doesn\'t work. How can I do i

3条回答
  •  情书的邮戳
    2020-12-09 06:16

    Here is the code snippet I did for this. Remove the "consume" from your @RequestMapping annotation because you are not using that in your method.

    @RestController
    public class GreetingsController
    {
        @RequestMapping(value = "greetings", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody
        List greeting() {
            Greeting greeting1 = new Greeting(1, "One");
            Greeting greeting2 = new Greeting(2, "Two");
            List list = new ArrayList<>();
            list.add(greeting1);
            list.add(greeting2);
            return list;
        }
    
        public class Greeting
        {
            private String message;
            private int count;
    
            public Greeting(int count, String message)
            {
                this.count = count;
                this.message = message;
            }
    
            public String getMessage()
            {
                return message;
            }
    
            public void setMessage(String message)
            {
                this.message = message;
            }
        }
    }
    

提交回复
热议问题