我正在对外部服务 A 进行远程调用,它会将响应作为 json 返回,然后使用对象映射器反序列化为MyResponse
对象。之后,在我当前的服务中,我需要将此对象和输出附加到 UI。
MyResponse
服务 A中的字段之一是布尔值,我只希望我的 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" })
:当 value 为 false 时,这可以解决问题,但当 value 为 true 时,它也不包含该字段 @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
: 当值为 时false
,这会将字段反序列booleanValue
化为 false,因此我返回的myResponse/writeValue
字段仍将具有 UI。对此有任何其他建议吗?
编写自己的序列化程序
public class MyResponseSerializer extends JsonSerializer<MyResponse> {
@Override
public void serialize(MyResponse myResponse, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("stringValue", myResponse.getStringValue());
jsonGenerator.writeNumberField("intValue", myResponse.getIntValue());
if (myResponse.isBooleanValue()) {
jsonGenerator.writeBooleanField("booleanValue", myResponse.isBooleanValue());
}
jsonGenerator.writeEndObject();
}
}
使用 Objectmapper 注册它
@Test
public void test3() throws IOException {
MyResponse response1 = new MyResponse("response1", 1, true);
MyResponse response2 = new MyResponse("response2", 1, false);
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyResponse.class, new MyResponseSerializer());
objectMapper.registerModule(module);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response1));
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response2));
}
看这个教程
当我看到您无法修改 MyResponse 以添加注释时,我编辑了原始答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句