如何使用Spring Boot返回一组对象?

编程入门 行业动态 更新时间:2024-10-19 05:19:08
本文介绍了如何使用Spring Boot返回一组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我做了关于Spring Boot的课程,它运行良好.但是,如果我想返回一组对象怎么办?我尝试做此但这是行不通的.我该怎么做呢?

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 it correctly ?

具有一个对象(有效):

With one object (it works):

@RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue = "World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); }

有很多对象(无效):

With many objects (it doesn't work):

@RequestMapping(value = "/greeting", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Greeting> greeting() { Greeting greeting1 = new Greeting(1, "One"); Greeting greeting2 = new Greeting(2, "Two"); List<Greeting> list = new ArrayList<>(); list.add(greeting1); list.add(greeting2); return list; }

推荐答案

如果将原始方法与新方法(使用List)进行比较,则会发现一些区别.

If you compare your original method to your newly made one (with a List), you'll notice a few differences.

首先,在@RequestMapping批注中,您现在正在使用属性consumes和produces. produces在这里不是问题,因为您生成的响应应该是JSON. 但是,您什么都没消费,因此您应该放弃consumes.

First of all, within the @RequestMapping annotation you're now using the properties consumes and produces. produces is not a problem here, because you are producing a response that should be JSON. However you're not consuming anything, so you should leave away the consumes.

@RequestMapping(value = "/greeting", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<Greeting> greeting() { Greeting greeting1 = new Greeting(1, "One"); Greeting greeting2 = new Greeting(2, "Two"); List<Greeting> list = new ArrayList<>(); list.add(greeting1); list.add(greeting2); return list; }

作为旁注,您可能还会注意到您使用了@ResponseBody批注.将其放在此处不会引起任何错误,但不是必须的,因为如果您正确地遵循了Spring教程,则应该使用@RestController注释控制器,并已这样做,您已经告诉Spring它将使用响应身体.

As a sidenote, you might also notice that you used the @ResponseBody annotation. Putting it here won't cause any errors, but it is not necessary, because if you followed the Spring tutorial correctly, you should have annotated your controller with @RestController and by doing that, you already tell Spring that it will use a response body.

更多推荐

如何使用Spring Boot返回一组对象?

本文发布于:2023-05-23 15:03:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   对象   Spring   Boot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!