postman
我的 header “Content-Type”是“application/json”,我用 JSON 发送它, 看起来像这样...
{
"category": "House Maintenance"
}
申请
Category.java(模型)
@Data
@Entity
@Table(name = "Categories")
public class Category implements Serializable{
private static final long serialVersionUID = -8577891700634111561L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "category", nullable = false)
private String category;
public Category(String category){
super();
this.category = category;
}
public Category(){
}
}
CategoryServiceImpl.java(保存方法)
@Override
public void save(Category newCategory) {
categoryRepository.save(newCategory);
}
CategoryController.java(请求)
@RequestMapping(value = "/categories", method = RequestMethod.POST)
public void addCategory(@RequestBody String categoryName){
Category newCategory = new Category(categoryName);
categoryService.save(newCategory);
}
最佳答案
您在 Controller 方法中将请求转换为字符串,因此您收到请求的整个正文并将类别字段设置为整个 json 字符串。
您想要做的是 Spring Boot 已经为您提供了转换后的 dto:
@RequestMapping(value = "/categories", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addCategory(@RequestBody Category category){
categoryService.save(category);
}
如果您不想将实体与请求耦合,则需要引入一个额外的类,例如CreateCategoryDto
:
@Data
public class CreateCategoryDTO{
@JsonProperty(value = "category")
private String category;
}
(我假设您使用的是 Lombok 和 Jackson。添加注释 @JsonProperty(value = "category")
只是为了说明如何将 Java 字段名称与 Json 名称解耦。 )
Controller 就变成了
@RequestMapping(value = "/categories", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addCategory(@RequestBody CreateCategoryDto categoryDto){
Category newCategory = new Category(categoryDto.getCategory());
categoryService.save(newCategory);
}
关于java - Spring boot 的 Postman Post 请求会保存整个 JSON 正文,而不仅仅是字段值。我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60744774/