我致电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)
,但没有运气。
在这种情况下,有没有办法检索另一个对象(或某种回调)?
答案 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();
}