领域:如何将 int 设置为可为空,以便如果它从 json 获取值 "null",则可以忽略它
Realm: How can I set an int to nullable, so that if it gets the value "null" back from the json, it can be ignored
我有以下对象:
@RealmClass
public class TripStop extends RealmObject implements Serializable {
@Nullable
private int arrival_time;
private String address;
@PrimaryKey
private int id;
@Nullable
private int departure_time;
private Destination place;
private CoordLocation location;
public int getArrival_time() {
return arrival_time;
}
public void setArrival_time(int arrival_time) {
this.arrival_time = arrival_time;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDeparture_time() {
return departure_time;
}
public void setDeparture_time(int departure_time) {
this.departure_time = departure_time;
}
public Destination getPlace() {
return place;
}
public void setPlace(Destination place) {
this.place = place;
}
public CoordLocation getLocation() {
return location;
}
public void setLocation(CoordLocation location) {
this.location = location;
}
}
但每次我收到一个 json 响应,其中一个 int(或原语)为 null,我在 Realm 中得到一个错误:
08-29 16:45:59.220: I/WSCalls(6370): 错误:尝试将不可为空的字段 'departure_time' 设置为空。
我从 Realm 3.5 了解到可以设置空值或设置默认版本,但我还没有做到。
这怎么可能?我看到 @Nullable 没有帮助
首先:
int
是原始数据类型,不能与 null
.
赋值
解法:
您可以将类型更改为 Integer
。 Integer
可以包含 null
,但由于 boxing/unboxing 会增加一些开销。
(参见:https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html)
我有以下对象:
@RealmClass
public class TripStop extends RealmObject implements Serializable {
@Nullable
private int arrival_time;
private String address;
@PrimaryKey
private int id;
@Nullable
private int departure_time;
private Destination place;
private CoordLocation location;
public int getArrival_time() {
return arrival_time;
}
public void setArrival_time(int arrival_time) {
this.arrival_time = arrival_time;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDeparture_time() {
return departure_time;
}
public void setDeparture_time(int departure_time) {
this.departure_time = departure_time;
}
public Destination getPlace() {
return place;
}
public void setPlace(Destination place) {
this.place = place;
}
public CoordLocation getLocation() {
return location;
}
public void setLocation(CoordLocation location) {
this.location = location;
}
}
但每次我收到一个 json 响应,其中一个 int(或原语)为 null,我在 Realm 中得到一个错误:
08-29 16:45:59.220: I/WSCalls(6370): 错误:尝试将不可为空的字段 'departure_time' 设置为空。
我从 Realm 3.5 了解到可以设置空值或设置默认版本,但我还没有做到。 这怎么可能?我看到 @Nullable 没有帮助
首先:
int
是原始数据类型,不能与 null
.
解法:
您可以将类型更改为 Integer
。 Integer
可以包含 null
,但由于 boxing/unboxing 会增加一些开销。
(参见:https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html)