我有一个json:
{
"clientId": "1",
"appName": "My Application",
"body": "Message body",
"title": "Title"
"data": {
"key1": "value1",
"key2": "value2"
}
}
和DTO:
@Data
public class PushNotificationDto {
private Long clientId;
private String appName;
private String body;
private String title;
private String data;
}
我正在使用SpringBoot,我的@RestController看起来像这样:
@RestController
@AllArgsConstructor
public class PushNotificationController {
private PushNotificationService pushNotificationService;
@PostMapping("/push-notification")
void sendPushNotification(@RequestBody PushNotificationDto pushNotification) {
pushNotificationService.send(pushNotification);
}
}
由于json对象中的数据字段实际上是一个对象,但在我的DTO中它是一个String,所以我得到了一个异常:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Can not deserialize instance of java.lang.String out of START_OBJECT token;
nested exception is com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of java.lang.String out of START_OBJECT token
我该怎么做才能成功执行这样的反序列化?
在您的请求对象中,您有一个data
数组。
"data": {
"key1": "value1",
"key2": "value2"
}
但是在您的PushNotificationDto
对象中,您有String data
。这就是你出现这个错误的原因。要解决此错误,您可以将String data
更改为Map<String,String>
这也可能是一个部署问题。如果您在进行更改后部署了pojo,使用该pojo的服务仍在使用旧的类文件,那么就会出现问题。如果这是你。然后首先部署pojo,然后部署所有使用它的服务。这就是我的遭遇。