[英]Jackson ignore properties using the same class
我的问题是关于我想使用同一个类来反序列化和重新序列化两个不同的Jsons的事实。 我试着更好地解释一下。 我有这些Jsons:
//JSON A
{
"flavors": [
{
"id": "52415800-8b69-11e0-9b19-734f1195ff37",
"name": "256 MB Server",
"ram": 256,
"OS-FLV-DISABLED:disabled":true
"links": [
{
"rel": "self",
"href": "http://www.myexample.com"
},
{
"rel": "bookmark",
"href":"http://www.myexample.com"
}
]
},
...
}
//JSON B
{
"flavors": [
{
"id": "52415800-8b69-11e0-9b19-734f1195ff37",
"name": "256 MB Server",
"links": [
{
"rel": "self",
"href": "http://www.myexample.com"
},
{
"rel": "bookmark",
"href":"http://www.myexample.com"
}
]
},
...
}
正如您所看到的,除了“ram”和“OS-FLV-DISABLED:disabled”之外,JSON B具有JSON A的所有字段。 我使用的类如下:
public class Flavor {
private String name;
private List<Link> links;
private int ram;
private boolean OS_FLV_DISABLED_disabled;
//constructor and getter/setter
}
@XmlRootElement
public class GetFlavorsResponse {
private List<Flavor> flavors;
//constructor and getter/setter
}
此外,在getter方法的上方是OS_FLV_DISABLED_disabled我已经注释@XmlElement(name = "OS-FLV-DISABLED:disabled")
否则Jackson不会识别此属性。 这是情况的计划:
当我收到JSON A时没有问题,JSON结果再次是JSON A; 但是当我收到JSON B时,进程反序列化 - 序列化的结果是:
//JSON C
{
"flavors": [
{
"id": "52415800-8b69-11e0-9b19-734f1195ff37",
"name": "256 MB Server",
"ram": 0,
"OS-FLV-DISABLED:disabled":false
"links": [
{
"rel": "self",
"href": "http://www.myexample.com"
},
{
"rel": "bookmark",
"href":"http://www.myexample.com"
}
]
},
...
}
现在我认为杰克逊设置的类属性不是Json中的默认值,即“ram”和“OS-FLV-DISABLED:disabled”分别为0和false 。 所以我把注释
@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
就在Flavor类之上。 这有效但问题是,当我收到JSON A,其中“ram”和“OS-FLV-DISABLED:disabled”具有值0和false (可能的情况)时,上面提到的过程的结果是JSON B,因为这些两个字段被忽略。 所以确定这不是我的问题的解决方案,我读到有些人建议使用@JsonView或@JsonFilter,但我不明白如何在这种情况下应用这些Jackson功能。 我希望我很清楚,并提前感谢你的帮助。
您可以尝试的一件事是将ram
和OS_FLV_DISABLED_disabled
分别OS_FLV_DISABLED_disabled
为Integer
和Boolean
类型。 这样,如果这两个属性的json中没有值,那么它们将为null。 并使用此注释@JsonInclude(Include.NON_NULL)
来避免序列化null属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.