如何从 START_OBJECT 令牌中反序列化 java.lang.String 的实例
How to deserialize instance of java.lang.String out of START_OBJECT token
我有一个 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 中它是一个字符串,我得到一个异常:
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 的服务仍在使用旧的 class 文件,那么就会出现问题。如果这是你。然后先部署pojo,再部署所有使用它的服务。这就是发生在我身上的事情。
我有一个 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 中它是一个字符串,我得到一个异常:
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 的服务仍在使用旧的 class 文件,那么就会出现问题。如果这是你。然后先部署pojo,再部署所有使用它的服务。这就是发生在我身上的事情。