0

我有一个看起来像这样的类 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"}"

不过,我需要“操作”这个词只是“操作”。据说,有一种方法可以配置 ObjectMapper,当它读取“操作”时,它会将其转换为“操作”,但我不知道该怎么做。有人知道吗?

4

1 回答 1

0

您可以使用 @JsonProperty 注释

public static class Diff {

    private String path;
    private String value;

    @JsonProperty("op")
    private Operation operation;
}

[更新]
因为你没有访问类,你可以使用 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;
    }
}
于 2016-04-14T19:06:29.950 回答