如何从START_OBJECT令牌中反序列化java.lang.String实例

时间:2018-12-12 16:14:14

标签: java json spring-boot json-deserialization jackson-databind

我有一个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

我该怎么做才能使反序列化成功执行?

1 个答案:

答案 0 :(得分:2)

在您的请求对象中,您有一个data数组。

"data": {
  "key1": "value1",
  "key2": "value2"
}

但是在您的PushNotificationDto对象中,您有String data。这就是您收到此错误的原因。要解决此错误,您可以将String data更改为Map<String,String>