如何配置 ObjectMapper 以仅映射使用 JsonProperty 注释的属性? (不一定是这个特定的注释,但这似乎是最明智的)
我正在寻找类似于 Gson 的 @Expose 注释和 GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() 序列化程序 Example 的东西。
class Foo {
public String secret;
@JsonProperty
public String biz;
}
class FooTest {
public static void main(String[] args) {
ObjectMapper m = new ObjectMapper();
// configure the mapper
Foo foo = new Foo();
foo.secret = "secret";
foo.biz = "bizzzz";
System.out.println(m.writeValueAsString(foo));
// I want {"biz": "bizzzz"}
m.readValue("{\"secret\": \"hack\", \"biz\": \"settable\"}", Foo.class);
// I want this to throw an exception like secret does not exist
}
}
谢谢,赎金
最佳答案
从 duplicate question 开始,除了我也不希望使用字段。
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
关于java - 如何配置 Jackson ObjectMapper 以仅显示白名单属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9299013/