【问题标题】:Map nested json to a pojo with raw json value将嵌套的 json 映射到具有原始 json 值的 pojo
【发布时间】:2019-01-31 21:03:29
【问题描述】:

我有一个嵌套的 json pojo,其中 json 的嵌套部分用 @JsonRawValue 标记。我正在尝试将其与其余模板进行映射,但出现错误 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;

}

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

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

    ResponseEntity<ResponseDTO> resonseEntity = restTemplate.exchange(URI, HttpMethod.POST, requestEntity, ResponseDTO.class);

我看到了这个异常:

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"])

【问题讨论】:

    标签: java json spring rest jackson


    【解决方案1】:

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

    @JsonRawValue 用于将对象序列化为 JSON 格式。这是一种指示字符串字段按原样发送的方法。换句话说,目的是告诉 Jackson 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();
        }
    }
    

    【讨论】:

    • @Ankit,如果这个答案有帮助,请采纳。
    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 2017-03-31
    • 2014-04-08
    • 2021-07-06
    • 1970-01-01
    • 2020-09-01
    • 2021-12-15
    • 2023-01-11
    相关资源
    最近更新 更多