Java @JsonIgnoreProperties 对已知和未知属性的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44317816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@JsonIgnoreProperties usage for both known and unknown properties
提问by user1242321
My current annotation for ignoring the known properties for a JPA entity is:
我当前忽略 JPA 实体的已知属性的注释是:
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler","created","updated","createdBy","lastUpdatedBy"})
In addition to ignoring these class properties, I would also like to ignore any unknown properties that the server receives. I know the alone way to ignore the unknown properties by the following annotation:
除了忽略这些类属性之外,我还想忽略服务器接收到的任何未知属性。我知道通过以下注释忽略未知属性的唯一方法:
@JsonIgnoreProperties(ignoreUnknown=true)
But not sure how to add this to my current annotation given above. I tried multiple methods ?s below but none seem to work and I could not find an example online for this scenario.
但不确定如何将其添加到我上面给出的当前注释中。我在下面尝试了多种方法? s 但似乎都没有工作,我无法在网上找到这种情况的示例。
Any example or leads on documentation would also help.
任何关于文档的示例或线索也会有所帮助。
采纳答案by cassiomolin
Set ignoreUnknown
to true
and define the names of properties to ignore in the value
element:
设置ignoreUnknown
于true
和定义属性中忽略的名字value
元素:
@JsonIgnoreProperties(ignoreUnknown = true,
value = {"hibernateLazyInitializer", "handler", "created"})
How does it work?
它是如何工作的?
Have a look at this quote from the documentation(highlight is mine):
看看文档中的这句话(重点是我的):
In its simplest form, an annotation looks like the following:
@Entity
The at sign character (
@
) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name isOverride
:@Override void mySuperMethod() { ... }
The annotation can include elements, which can be named or unnamed, and there are values for those elements:
@Author(name = "Benjamin Franklin", date = "3/27/2003") class MyClass() { ... }
or
@SuppressWarnings(value = "unchecked") void myMethod() { ... }
If there is just one element named
value
, then the name can be omitted, as in:@SuppressWarnings("unchecked") void myMethod() { ... }
以最简单的形式,注释如下所示:
@Entity
at 符号字符 (
@
) 向编译器指示后面的内容是注释。在以下示例中,注释的名称是Override
:@Override void mySuperMethod() { ... }
注释可以包含元素,可以命名或未命名,并且这些元素有值:
@Author(name = "Benjamin Franklin", date = "3/27/2003") class MyClass() { ... }
或者
@SuppressWarnings(value = "unchecked") void myMethod() { ... }
如果只有一个名为 的元素
value
,则可以省略名称,如下所示:@SuppressWarnings("unchecked") void myMethod() { ... }
Other way to handle unknown properties
处理未知属性的其他方法
To ignore unknown properties, you also could do:
要忽略未知属性,您还可以执行以下操作:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);