You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot RESTful服务:如何提交JSON数组及类中tags字段?

Hey,这两个问题都是Spring Boot REST开发中非常常见的场景,我来给你一步步拆解解决:

1. 如何向Spring Boot REST服务提交JSON数组?

首先要明确:提交JSON数组的核心是请求头设置Content-Type: application/json,然后在Controller中用@RequestBody注解接收数组或集合类型的参数。

举个实际场景的例子:假设你要批量提交用户数据,先定义一个简单的DTO(数据传输对象):

public class UserDto {
    private String name;
    private Integer age;
    
    // 记得添加getter、setter,或者用Lombok的@Data注解简化
}

然后在Controller中编写接收接口:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PostMapping("/batch")
    public ResponseEntity<String> batchAddUsers(@RequestBody List<UserDto> userList) {
        // 这里可以执行批量保存、业务处理等逻辑
        return ResponseEntity.ok("成功接收" + userList.size() + "条用户数据");
    }
}

用curl测试的话,请求体直接传JSON数组即可:

curl -X POST http://localhost:8080/api/users/batch \
  -H "Content-Type: application/json" \
  -d '[
    {"name": "张三", "age": 25},
    {"name": "李四", "age": 30}
  ]'

如果你的场景不需要复杂DTO,也可以直接接收基础类型数组,比如@RequestBody String[] ids或者@RequestBody Integer[] numbers。

2. 提交包含JSON数组类型tags字段的类

假设你已经定义了包含tags数组的实体/DTO,比如:

public class ArticleDto {
    private String title;
    private String content;
    private List<String> tags; // 这个就是你说的JSON数组类型字段
    
    // getter、setter或@Data注解
}

处理起来更简单:Controller直接接收这个DTO对象,Spring会自动把JSON中的数组映射到tags字段里:

@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    @PostMapping
    public ResponseEntity<ArticleDto> createArticle(@RequestBody ArticleDto article) {
        // 比如打印标签列表验证是否接收成功
        System.out.println("文章标签:" + article.getTags());
        return ResponseEntity.ok(article);
    }
}

对应的请求体中,tags字段要写成JSON数组格式,用curl测试示例:

curl -X POST http://localhost:8080/api/articles \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Spring Boot REST实战",
    "content": "这是一篇关于REST接口开发的文章",
    "tags": ["Java", "Spring Boot", "RESTful"]
  }'

额外注意事项

  • 一定要确保请求头的Content-Type是application/json,否则Spring无法正确解析JSON数据
  • 如果JSON中的键名和DTO字段名不一致,可以用@JsonProperty("tag_list")注解指定别名
  • 用Postman/Insomnia等工具测试时,直接选Body为Raw -> JSON格式,粘贴对应的JSON内容即可

内容的提问来源于stack exchange,提问作者A. Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:54:19