【问题标题】:Change return type if it can't be deserialized in rest template?如果不能在休息模板中反序列化,请更改返回类型?
【发布时间】:2026-01-07 04:55:01
【问题描述】:

我打电话给restTemplate

restTemplate.exchange(uri, HttpMethod.GET, prepareHttpEntity(), MyDeserializedClass.class);

MyDeserializedClass:

public class MyDeserializedClass {

    private final String id;
    private final String title;

    @JsonCreator
    public MyDeserializedClass(@JsonProperty("id") String id,
                    @JsonProperty("title") String title) {
        this.pageId = pageId;
        this.title = title;
    }
}

当 json 中没有对象时,我得到 MyDeserializedClassnull 值。

我尝试使用注释 MyDeserializedClass @JsonInclude(JsonInclude.Include.NON_NULL)@JsonIgnoreProperties(ignoreUnknown = true) 但没有运气。

有没有办法在这种情况下检索另一个对象(或某种回调)?

【问题讨论】:

  • null 或某种 MyDeserializedClass 子类而不是 MyDeserializedClass with null values 为您修复它吗?
  • 为什么不返回字符串而使用jackson来映射呢?如果为 null 将很容易检测到。
  • @varren 如果我得到 null 而不是具有 null 值的对象,那么它会满足我

标签: json spring resttemplate json-deserialization


【解决方案1】:

您可以使用静态函数作为主要的@JsonCreator 而不是构造函数

public class MyDeserializedClass {

    private final String id;
    private final String title;

    public MyDeserializedClass () {}

    @JsonCreator
    public static MyDeserializedClass JsonCreator(@JsonProperty("id") String id, @JsonProperty("title") String title){
        if (id == null || title == null) return null;
        //or some other code can go here

        MyDeserializedClass myclass = new MyDeserializedClass();

        myclass.id = id; // or use setters
        myclass.title = title;

        return myclass;
    }
}

这样您可以返回null 或某种MyDeserializedClass 子类,而不是MyDeserializedClass with null values

【讨论】:

    【解决方案2】:

    您可以尝试自己反序列化对象,即:

    ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, prepareHttpEntity(), String.class);
    try {
       MyDeserializedClass myClass = new ObjectMapper().readValue(response.body, MyDeserialized.class);
       return ResponseEntity.ok(myClass);
    } catch(IOException e) {
       //log exception
       return ResponseEntity.notFound().build();
    }
    

    【讨论】:

      最近更新 更多