Spring Boot添加文章至分类时JSON解析错误求助
解决Spring Boot中创建文章时的JSON解析错误
错误原因
你的请求JSON中category字段传递的是字符串值"food",但Post实体类里的category字段是Category类型的对象。Jackson在反序列化时,无法将字符串直接转换为Category实例——因为Category类没有提供接收字符串参数的构造方法或工厂方法,导致抛出解析错误。
解决方案
提供三种可行的解决思路,你可以根据业务需求选择:
方案1:调整请求JSON结构,传递Category对象
将请求中的category从字符串改为对象格式,传递分类的属性(比如name或id):
{ "title":"Second post with post response class message and post object", "description": "you can test the api here!", "category": {"name": "food"} }
如果业务要求关联已存在的分类,可以传递分类的id:
{ "title":"Second post with post response class message and post object", "description": "you can test the api here!", "category": {"id": 1} }
方案2:给Category类添加字符串参数的构造方法
在Category类中添加接收name的构造方法,并通过@JsonCreator注解告诉Jackson使用该方法反序列化字符串:
@Data @Entity @NoArgsConstructor @AllArgsConstructor public class Category { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @JsonCreator public Category(String name) { this.name = name; } }
⚠️ 注意:这种方式会直接创建新的Category实例,适合允许通过新建分类来关联文章的场景;如果需要关联已有分类,这个方案不适用。
方案3:修改请求DTO,在服务层处理分类关联
这是更符合业务逻辑的做法:
- 修改
CreatePostRequest,用String类型接收分类名称,而非直接用Category对象:
@Data public class CreatePostRequest { private String title; private String description; // 用@JsonProperty映射请求中的"category"字段 @JsonProperty("category") private String categoryName; }
- 调整服务层方法,根据分类名称查询或创建分类后再关联到文章:
@Override public Post createPost(CreatePostRequest postRequest, String jwt) throws Exception { User user = userService.findUserByJwtToken(jwt); // 查询已有分类,不存在则创建 Category category = categoryRepository.findByName(postRequest.getCategoryName()); if (category == null) { category = new Category(); category.setName(postRequest.getCategoryName()); category = categoryRepository.save(category); } Post newPost = new Post(); newPost.setTitle(postRequest.getTitle()); newPost.setDescription(postRequest.getDescription()); newPost.setCreatedAt(LocalDateTime.now()); newPost.setCategory(category); newPost.setUser(user); return postRepository.save(newPost); }
同时更新服务接口,移除Category类型的参数:
public Post createPost(CreatePostRequest request, String jwt) throws Exception;
这种方式不需要修改请求JSON,同时能灵活处理"关联已有分类"或"创建新分类"的业务需求。
内容的提问来源于stack exchange,提问作者Neo
相关产品推荐
相关产品推荐

