我正在使用Moshi
来解析JSON
对JAVA
对象的响应。问题是,当服务器不发送嵌套类的键值时,moshi会将其分配给null
。
将默认值分配给基元和String等有效时,实例化嵌套类无效。
父级客户类别-
public class Customer {
@Json(name = "id")
Integer id;
@Json(name = "test")
String test = "I'm batman!";
@Json(name = "default_address")
Address defaultAddress = new Address(-1, -1);
public Integer getId() {
return id;
}
public String getTest() {
return test;
}
}
地址类别-
public class Address {
@Json(name = "id")
Integer id;
@Json(name = "customer_id")
Integer customerId;
public Address(int id, int cusID) {
this.id = id;
this.customerId = cusID;
}
public Integer getCustomerId() {
return customerId;
}
public Integer getId() {
return id;
}
}
虽然响应中不包含任何名称为test
的键,但它可以工作。但是,当服务器不发送default_address
密钥时,defaultAddress
将设置为null
。