我有一个类似于Diff的类:
public class Diff {
private String path;
private String value;
private Operation operation;
public enum Operation {
ADD, REPLACE, REMOVE
}
// getters and setters
}
我想使用以下调用创建一个json节点:
ObjectMapper mapper = new ObjectMapper();
mapper.valueToTree(diffObject);
如果我有这样的差异:
Diff diff = new Diff();
diff.setPath("/path");
diff.setValue("value");
diff.setOperation(Operation.REPLACE);
这样做的:
mapper.valueToTree(diff);
将返回:
"{"path":"/path", "value":"value","operation":"REPLACE"}"
我需要"操作"但是,只是" op"据说,有一种方法可以配置ObjectMapper,以便在何时读取"操作",它会将其转换为" op",但我不知道如何去做吧。有人知道吗?
答案 0 :(得分:0)
您可以使用@JsonProperty注释
public static class Diff {
private String path;
private String value;
@JsonProperty("op")
private Operation operation;
}
<强> [UPDATE] 强>
因为您无权访问该类,您可以使用ByteBuddy来修改该类吗? :)
例如:
@Test
public void byteBuddyManipulation() throws JsonProcessingException, IllegalAccessException, InstantiationException {
ObjectMapper objectMapper = new ObjectMapper();
AnnotationDescription annotationDescription = AnnotationDescription.Builder.forType(JsonProperty.class)
.define("value", "op")
.make();
Class<? extends Diff> clazz = new ByteBuddy()
.subclass(Diff.class)
.defineField("operation", Diff.Operation.class)
.annotateField(annotationDescription)
.make()
.load(Diff.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
Diff diffUpdated = clazz.newInstance();
diffUpdated.setOperation(Diff.Operation.ADD);
objectMapper.valueToTree(diffUpdated); //returns "op":"ADD"
}
[更新2]
或者只是创建Diff的子类并隐藏操作字段
public static class YourDiff extends Diff {
@JsonProperty("op")
private Operation operation;
@Override public Operation getOperation() {
return operation;
}
@Override public void setOperation(Operation operation) {
this.operation = operation;
}
}