将嵌套的 json 映射到具有原始 json 值的 pojo

Ank*_*kit 2 java rest spring json jackson

我有一个嵌套的 json pojo,其中 json 的嵌套部分用@JsonRawValue. 我正在尝试使用 rest 模板进行映射,但出现错误 JSON 解析错误:Cannot deserialize instance of java.lang.String out of START_OBJECT token;

嵌套异常是com.fasterxml.jackson.databind.exc.MismatchedInputException.

这是我的响应对象的样子:

import com.fasterxml.jackson.annotation.JsonRawValue;

public class ResponseDTO {

    private String Id;
    private String text;
    @JsonRawValue
    private String explanation;

    //getters and setters;

}
Run Code Online (Sandbox Code Playgroud)

explanation映射到字符串的 json在哪里。这适用于邮递员,招摇,我在响应中看到解释为 json。

但是当我使用 Rest Template 测试它时:

    ResponseEntity<ResponseDTO> resonseEntity = restTemplate.exchange(URI, HttpMethod.POST, requestEntity, ResponseDTO.class);
Run Code Online (Sandbox Code Playgroud)

我看到这个例外:

org.springframework.web.client.RestClientException: Error while extracting 
response for type [class com.**.ResponseDTO] and content type 
[application/json;charset=utf-8]; nested exception is 
org.springframework.http.converter.HttpMessageNotReadableException: JSON 
parse error: Cannot deserialize instance of java.lang.String out of 
START_OBJECT token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of java.lang.String out of START_OBJECT token
     at [Source: (PushbackInputStream); line: 1, column: 604] (through 
reference chain: com.****.ResponseDTO["explanation"])
Run Code Online (Sandbox Code Playgroud)

Joã*_*aro 5

Jackson 告诉您它不能在字符串中插入对象(在错误日志中)。

@JsonRawValue对象JSON格式的串行化过程中使用。这是一种指示 String 字段按原样发送的方式。换句话说,目的是告诉杰克逊该字符串是一个有效的 JSON,应该在不转义或引用的情况下发送。

您可以做的是为 Jackson 提供一个自定义方法来设置字段值。使用JsonNode作为参数将迫使杰克逊通过“原始”值。从那里你可以得到字符串表示:

public class ResponseDTO {

    private String Id;
    private String text;
    private String explanation;

    //getters and setters;

    @JsonProperty("explanation")
    private void unpackExplanation(JsonNode explanation) {
        this.explanation = explanation.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)