如果无法在rest模板中反序列化,请更改返回类型?

时间:2016-02-04 11:21:54

标签: json spring resttemplate json-deserialization

我致电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中没有对象时,我的MyDeserializedClass值为null

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用静态函数作为主@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

答案 1 :(得分:0)

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

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();
}