如何从JSON REST请求中获取ArrayList/List并转换为含列表属性的POJO
如何从JSON REST请求中获取List并转换为带列表属性的POJO
看起来你在处理REST请求转POJO时遇到了列表属性的问题,我来帮你梳理正确的做法,顺便指出你代码里的几个小问题:
首先,修正你的领域POJO(DocumentProps)
你的原代码给POJO加了@Service注解,这是不对的——@Service是用来标记业务逻辑层的类,而我们的DocumentProps是单纯的领域模型,不需要这个注解。另外,你的List properties没有指定泛型,Jackson没法正确反序列化列表里的元素类型。
这里是修正后的POJO代码,我用Lombok的@Data来简化getter/setter的编写(如果不用Lombok,你需要手动写所有属性的getter和setter):
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data @JsonIgnoreProperties(ignoreUnknown = true) public class DocumentProps { @JsonProperty("name") private String name; @JsonProperty("type") private String type; // 给List指定泛型,这里假设properties是字符串列表 // 如果是自定义对象,比如每个属性是键值对,就改成List<Property> @JsonProperty("properties") private List<String> properties; } // 如果你需要自定义Property类型(比如键值对),可以加这个类 @Data @JsonIgnoreProperties(ignoreUnknown = true) class Property { @JsonProperty("key") private String key; @JsonProperty("value") private String value; }
然后,编写正确的控制器逻辑
你的原代码里在控制器中@Autowired了DocumentProps,这也是错误的——POJO是用来接收请求数据的,不是Spring容器里的Bean,应该在请求方法的参数里接收。
场景1:POST请求接收JSON请求体
如果前端是通过POST请求发送JSON数据(这是最常见的场景),用@RequestBody注解就能让Spring自动把JSON转换成DocumentProps对象:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class DocumentController { // 类名建议用大驼峰,符合Java规范 @PostMapping("/submit-document") public String handleDocumentSubmission(@RequestBody DocumentProps docProps) { // 直接使用docProps里的properties列表 System.out.println("文档名称:" + docProps.getName()); System.out.println("属性列表:" + docProps.getProperties()); // 这里可以写你的业务逻辑,比如保存到数据库等 return "请求处理成功,共收到" + docProps.getProperties().size() + "个属性"; } }
对应的请求JSON示例(如果是字符串列表):
{ "name": "用户手册", "type": "PDF", "properties": ["可下载", "中文", "最新版本"] }
场景2:GET请求接收列表参数
如果是GET请求,一般不会传JSON体,而是通过请求参数传递列表(多个参数用逗号分隔,或者重复参数名),这时候可以用@RequestParam接收,再手动构建POJO:
@GetMapping("/get-document") public String handleDocumentQuery( @RequestParam String name, @RequestParam String type, @RequestParam List<String> properties) { DocumentProps docProps = new DocumentProps(); docProps.setName(name); docProps.setType(type); docProps.setProperties(properties); // 后续处理逻辑 return "GET请求处理完成,属性数量:" + properties.size(); }
请求示例:http://localhost:8080/get-document?name=用户手册&type=PDF&properties=可下载&properties=中文
关键注意事项
- 必须有getter/setter:Spring的Jackson依赖需要通过getter/setter来访问POJO的属性,所以要么手动写,要么用Lombok的
@Data/@Getter/@Setter。 - 泛型不能少:
List必须指定泛型(比如List<String>或List<Property>),否则Jackson会把列表元素反序列成LinkedHashMap,而不是你想要的类型。 - 注解使用正确:
@RequestBody只能用于POST/PUT等有请求体的方法,GET请求用@RequestParam接收参数。
内容的提问来源于stack exchange,提问作者java
相关产品推荐
相关产品推荐

