我创建了一个简单的Web REST应用程序,该应用程序必须将“更改票证”保存到数据库中。但是,当我尝试使用JSON作为正文创建POST请求时,出现错误:
2020-11-28 14:06:10.449 DEBUG 14864 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 400 BAD_REQUEST
2020-11-28 14:06:10.453 DEBUG 14864 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for POST "/error", parameters={}
2020-11-28 14:06:10.455 DEBUG 14864 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2020-11-28 14:06:10.464 DEBUG 14864 --- [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2020-11-28 14:06:10.464 DEBUG 14864 --- [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Sat Nov 28 14:06:10 CET 2020, status=400, error=Bad Request, message=, path=/change/save}]
2020-11-28 14:06:10.476 DEBUG 14864 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 400
我正在使用Spring Boot 2,将MySQL作为DB和MapStruct将DTO转换为实体,反之亦然。我也使用Project Lombok摆脱了一些样板代码
我的控制器POST方法如下所示:
@RestController
@Slf4j
@RequestMapping({"/change"})
public class ChangeTicketController {
@PostMapping(value = "/save", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> save(@RequestBody @Validated ChangeTicketDto changeTicketDto){
ChangeTicket mappedChangeTicket = changeTicketMapper.changeTicketDtoToChangeTicket(changeTicketDto);
ChangeTicket savedTicket = changeService.save(mappedChangeTicket);
return ResponseEntity.created(URI.create(BASE_URL + "/save/" + savedTicket.getChangeId()))
.body("Change Ticket has been saved");
}
}
我要保存的实体如下所示:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class ChangeTicket extends BaseItem{
//some constructor
@NotBlank
private String changeId; // public ID set by user
@NotNull
@Enumerated(value = EnumType.STRING)
private ChangeType changeType;
@NotBlank
@Size(min = 15, max = 500)
@Column(length = 500)
private String description;
}
超类:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
public class BaseItem {
@JsonIgnore
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id; // Secret ID generated by DB
@Enumerated(value = EnumType.STRING)
@NotNull
@Column(name = "item_status")
private ItemStatus itemStatus;
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private Timestamp createdAt;
@UpdateTimestamp
@Column(name = "updated_at",updatable = true)
private Timestamp updatedAt;
@Column(name = "closed_at", updatable = false)
private Timestamp closedAt;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "incidentSolver_id", referencedColumnName = "id") // owning side
private IncidentSolver incidentSolver;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
这是我通过POSTMAN发送给POST请求的示例JSON代码:http:// localhost:8080 / change / save
{
"changeId": "86edd7ea-4c37-4dd9-a55c-aeea171e0b42",
"changeType": "OS_SETTINGS_CHANGE",
"description": "description",
"itemStatus": "OPEN",
"createdAt": "2020-11-28T12:51:58+00:00",
"updatedAt": "2020-11-28T12:55:08+00:00",
"closedAt":"",
"incidentSolver": [
{
"incidentId": "015f3e95-de08-4035-9052-9d40ad2b7af6",
"userName": "ThisDude"
}
],
"user": [
{
"userId": "3d00339a-5757-4ada-a316-6705ff603d96",
"userType": "CUSTOMER",
"userName": "WednesdayDude"
}
]
}
我不知道杰克逊不知道如何反序列化/序列化子对象和父对象是否存在问题,或者我是否在错误地构建我的Json。如果你需要查看我的服务类存储库,我将编辑此帖子以显示它们。
编辑:添加ChangeTicketDTO
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ChangeTicketDto extends BaseItemDto {
private String changeId; // public ID set by user
private ChangeType changeType;
private String description;
}
BaseItemDTO
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class BaseItemDto {
private ItemStatus itemStatus;
private Timestamp createdAt;
private Timestamp updatedAt;
private Timestamp closedAt;
private IncidentSolver incidentSolver;
private User user;
}
谢谢你们的帮助
我回来的是对我有用的解决方案。我试过测试,看看是什么导致了此问题,结果是,当你错误构造JSON请求主体时会发生此问题。
正如你在我的帖子中看到的那样,我正在使用JSON主体向控制器发送POST请求。但是,比起我想写一个将我的对象转换为JSON的测试方法的想法,这样我可以确保以正确的方式构造JSON。在这里你可以看到它:
@ExtendWith(MockitoExtension.class)
class ChangeServiceImplTest {
ChangeTicketDto changeTicketDto;
@Test
public void testConversionOfObject() throws JsonProcessingException {
changeTicketDto = changeTicketDto.builder().changeId("StringID")
.description("SOME TEXT")
.changeType(ChangeType.INSTALLATION_OF_OS)
.incidentSolver(IncidentSolver.builder().userName("DUDE").id("ID").build())
.user(User.builder().userName("USERNAME").userType(UserType.USER).build())
.closedAt(Timestamp.from(Instant.now()))
.createdAt(Timestamp.from(Instant.now()))
.updatedAt(Timestamp.from(Instant.now()))
.itemStatus(ItemStatus.OPEN)
.build();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(changeTicketDto);
System.out.println(json);
}
}
此方法返回一个简单的JSON字符串,如下所示:
{
"itemStatus": "OPEN",
"createdAt": 1607031646362,
"updatedAt": 1607031646362,
"closedAt": 1607031646361,
"incidentSolver": {
"incidentId": null,
"userName": "DUDE"
},
"user": {
"userId": null,
"userType": "USER",
"userName": "USERNAME"
},
"changeId": "StringID",
"changeType": "INSTALLATION_OF_OS",
"description": "SOME TEXT"
}
所以我创建了另一个到相同URL的POST请求,它起作用了!!!所以现在我知道,如果我将创建一个与我的objectt(及其父超类)不对应的错误的JSON,我将得到这种错误。非常感谢
这解决了您的问题吗?我今天看到您对我的问题的评论,以为我会与您核对。
是的,这实际上解决了我的问题。但是仍然感谢您的帮助:)