[英]JAXB (MOXy)- Unmarshalling null values
我在JSon與JAXB MOXy解組時遇到了麻煩。
以下是我要解析的JSON:
{
"accounts": [{
"description": "A",
"balance": 1000,
"balanceAvailable": 1000
},
{
"description": "B",
"balance": 1001,
"balanceAvailable": 1001
},
{
"description": "C",
"balance": 1002,
"balanceAvailable": 1002
}],
"cardPermissions": null,
"totalBalanceAvailable": 1046.19
}
這里的問題是字段“ cardPermissions
”。
我正在嘗試解組沒有“ cardPermissions
”字段(沒有@XmlElement批注和類屬性)的對象。
JAXB在解組此字符串時拋出NullPointerException,因為它是:
"cardPermissions": null
並不是:
"cardPermissions": "null"
要接受空值,我必須在POJO內添加字段cardPermissions(帶有@XmlElement批注)。
這樣,即使沒有getter和setter,JAXB仍可以正確地解組提供的JSON。
null和“ null”是完全不同的東西,但是我不想在POJO中包含此字段,因此我不得不忽略這些null值。
編輯
如果我像這樣包含根元素(“ customerInfo
”):
{
"customerInfo": {
"accounts": [{
"description": "B",
"balance": 1000,
"balanceAvailable": 1000
},
{
"description": "C",
"balance": 1001,
"balanceAvailable": 1001
},
{
"description": "D",
"balance": 1002,
"balanceAvailable": 1002
}],
"cardPermissions": null,
"totalBalanceAvailable": 1046.19
}
}
JSON可以正確解析,但是當我將JSON解組時,我不想包含root。
這是我的POJO:
@XmlRootElement(name = "customerInfo")
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerInfo {
@XmlElement(name = "name")
private String firstName;
@XmlElement(name = "surname")
private String lastName;
@XmlElement
private String customerId;
@XmlElement
private String email;
@XmlElement
private String cardPermissions; //This field has no getter and setter. I need it in order to parse correctly the JSON without the root node "customerInfo"
@XmlElement
private List<Account> accounts;
public CustomerInfo() {
}
public CustomerInfo(String firstName, String lastName, String emailAddress) {
this.firstName = firstName;
this.lastName = lastName;
this.email = emailAddress;
}
public String getFullName() {
return firstName + " " + lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
}
您有兩種選擇:
@XmlElement
中將required
的屬性設置為false
@XmlElement
為屬性name
設置一個值,然后刪除不需要的字段。 這樣,該字段將被忽略。 有關更多詳細信息,請轉到此舊帖子 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.