AndroidGeek AndroidGeek - 3 months ago 58
Android Question

Parsing Integer primitive types in Realm

Want to parse this JSON response in Realm but it always crashes for the categories:

[
{
"id": 32,
"name": "ABC",
"height": "49.5000",
"categories": [
14,15,16
]
}
]


Info.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;
}
}


This is how I parse when I receiving this 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()



public class 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;
}
}


The crash Log:



Caused by: java.lang.NumberFormatException: Expected an int but was 49.5000 at line 1 column 18581 path $[4].height

Answer

Your log says it all , the variable "height" on your json is not an int modify the model like this :

public class Info extends RealmObject {

    @PrimaryKey
    private Integer id;
    private String name;
    private Double height;
    private RealmList<RealmInt> categories;
}
Comments