将 json 字符串映射到与匿名 class 的接口

Mapping json string to interace with anonymous class

我有一个界面,我想将其用于 serialize/deserialize。我想省略一些字段。以下代码目前无法正常工作。

@JsonAutoDetect(fieldVisibility = Visibility.NONE)
public interface MyWrapper {
    //no annotation to not serialize
    String getMyField();

    //annotation to deserialize
    @JsonProperty("my_field")
    void setMyField();
}

您可以在方法上指定 @JsonIgnore 注释,或在 class 上指定 @JsonIgnoreProperties(value = {"myfield"}) 注释。

see examples here

编辑: 您使用的是哪个版本的杰克逊?因为在我使用的那个 (2.5) 中 @JsonIgnore@JsonProperty 一起使用效果很好。 另外,请注意 setter 需要接收一个参数才能由 Jackson

实际使用

固定接口 setter:

@JsonAutoDetect(fieldVisibility = Visibility.NONE)
public interface MyWrapper {
    @JsonIgnore
    String getMyField();

    // annotation to deserialize
    @JsonProperty("my_field")
    void setMyField(String f);
}

实施(这里没什么令人兴奋的)

public class Foo implements MyWrapper {
    private String myField;

    public Foo() {}
    public Foo(String f) {
        setMyField(f);
    }

    @Override
    public String getMyField() {
        return myField;
    }

    @Override
    public void setMyField(String f) {
        myField = f;
    }
}

测试:

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();

    // serialization - ignore field
    try {
        MyWrapper w = new Foo("value");
        String json = mapper.writeValueAsString(w);
        System.out.println("serialized MyWrapper: " + json);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // de-serialization - read field
    String json = "{\"my_field\":\"value\"}";
    try (InputStream is = new ByteArrayInputStream(json.getBytes("UTF-8"))) {
        MyWrapper w = (MyWrapper)mapper.readValue(is, Foo.class);
        System.out.println("deserialized MyWrapper: input: " + json + " ; w.getMyField(): " + w.getMyField());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

输出:

serialized MyWrapper: {}
deserialized MyWrapper: input: {"my_field":"value"} ; w.getMyField(): value