在Realm中解析整数原始类型

时间:2016-08-22 15:21:44

标签: android realm realm-list

想要在Realm中解析此JSON响应,但它总是崩溃类别:

[
  {
    "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;
    }
}

这是我收到此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

2 个答案:

答案 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;
}
相关问题