【发布时间】:2021-08-31 16:50:34
【问题描述】:
我正在远程调用外部服务 A,它会将响应作为 json 返回,然后使用对象映射器反序列化为 MyResponse 对象。之后,在我当前的服务中,我需要附加这个对象并输出到 UI。
来自服务 A 的 MyResponse 中的一个字段是布尔值,我只希望我的 UI 响应在值为 true 时包含此字段。 请注意,我无权修改我的 MyResponse 对象,因为它是只读的。所以我创建了一个 MixIn 类,也尝试了几种方法,但都没有成功..
public class MyResponse {
private String stringValue;
private int intValue;
// Expectation: only include this field when value true, and exclude it when value is false
private boolean booleanValue;
}
// @JsonIgnoreProperties(value = { "booleanValue" })
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
private static class MixInMyResponse {
}
// this would be my rest service eventually send myResponse to UI
public MyResponse readFromRemote() throws IOException {
String jsonAsString =
"{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":false}";
ObjectMapper mapper = new ObjectMapper();
// configure object mapper with mix in
mapper.getDeserializationConfig().addMixInAnnotations(MyResponse.class, MixInMyResponse.class);
MyResponse myResponse = mapper.readValue(jsonAsString, MyResponse.class);
// Expectation: writeValue needs only include booleanValue when value true, and exclude booleanValue when value is false
String writeValue = mapper.writeValueAsString(myResponse);
System.out.println(writeValue);
return myResponse;
}
- 使用
@JsonIgnoreProperties(value = { "booleanValue" }):当值为 false 时,这会解决问题,但当值为 true 时,它也不包含字段 - 使用
@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY):当值为false时,这会将字段booleanValue反序列化为false,因此我返回的myResponse/writeValue仍将具有此字段到UI。
对此有什么补充建议吗?
【问题讨论】:
-
@Chabo,是的,我尝试过这种方式,但没有运气,不确定是不是因为我正在使用 MixIn,因为我无法在原始类上修改...
标签: java jackson deserialization objectmapper