想在 Realm 中解析这个 JSON 响应,但它总是在类别中崩溃:
[
{
"id": 32,
"name": "ABC",
"height": "49.5000",
"categories": [
14,15,16
]
}
]
信息.java:
public class Info extends RealmObject {
@PrimaryKey
private Integer id;
private String name;
private Integer height;
private RealmList<RealmInt> categories;
}
RealmInt.java
public class RealmInt extends RealmObject{
private Integer val;
public RealmInt() {
}
public RealmInt(Integer val) {
this.val = val;
}
public Integer getVal() {
return val;
}
}
这是我收到此 JSON 时的解析方式:
String stringBody = response.body().string();
List<Info> newObjects = GsonIntWrapper.intBuilder().fromJson(stringBody, new TypeToken<List<Info>>(){}.getType());
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(newObjects);
GsonIntWrapper.intBuilder()
公共类 GsonIntWrapper {
public static Gson intBuilder(){
Type tokenInt = new TypeToken<RealmList<RealmInt>>(){}.getType();
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(tokenInt, new TypeAdapter<RealmList<RealmInt>>() {
@Override
public void write(JsonWriter out, RealmList<RealmInt> value) throws IOException {
// Ignore
}
@Override
public RealmList<RealmInt> read(JsonReader in) throws IOException {
RealmList<RealmInt> list = new RealmList<RealmInt>();
in.beginArray();
while (in.hasNext()) {
list.add(new RealmInt(in.nextInt()));
}
in.endArray();
return list;
}
})
.create();
return gson;
}
}
崩溃日志:
Caused by: java.lang.NumberFormatException: Expected an int but was 49.5000 at line 1 column 18581 path $[4].height