想要在Realm中解析此JSON响应,但它总是崩溃类别:
[
{
"id": 32,
"name": "ABC",
"height": "49.5000",
"categories": [
14,15,16
]
}
]
public class Info extends RealmObject {
@PrimaryKey
private Integer id;
private String name;
private Integer height;
private RealmList<RealmInt> categories;
}
public class RealmInt extends RealmObject{
private Integer val;
public RealmInt() {
}
public RealmInt(Integer val) {
this.val = val;
}
public Integer getVal() {
return val;
}
}
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 {
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
答案 0 :(得分:1)
在你的Json值中,“height”是 float ,但在你的RealmObject类(Info)中是 int
您可以看到此链接,这是一个类似的问题click here
答案 1 :(得分:1)
你的日志说明了一切,json上的变量“height”不是int修改模型如下:
public class Info extends RealmObject {
@PrimaryKey
private Integer id;
private String name;
private Double height;
private RealmList<RealmInt> categories;
}