[英]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.