【问题标题】:RealmList inside RealmObject not being populated from jsonRealmObject 中的 RealmList 未从 json 填充
【发布时间】:2015-07-23 20:40:12
【问题描述】:

所以我开始使用 Realm,到目前为止,它对于我的简单用例来说是不言自明的,但我发现从 Json 中创建一个包含 realmList 的领域对象并不会填充领域列表。这是我得到的:

public class User extends RealmObject{

    @PrimaryKey
    private int user_id;

    private RealmList<Place> places;

    private String fname;

    private String lname;

    private String birth_date;

    public RealmList<Place> getPlaces(){
        return this.places;
    }

    public void setPlaces(RealmList<Place>places) {
        this.places = places;
    }
}


public class Place extends RealmObject{

    private String place_name;
    //several other types all ints and Strings with getters and setters

}

这两个类在我的实际代码中都有适当的 getter 和 setter,我只是简单地包含了一个信息示例和所有重要信息来缩短它。

我正在使用改造,所有数据都以 jsonelements 的形式输入。

userService.requestProfile(new Callback<JsonElement>() {
        @Override
        public void success(JsonElement profileResponse, Response response) {
            Log.d(TAG, profileResponse.toString()); //shows raw response containing multiple places objects
            realm.beginTransaction();

            User user  = null;
            try {
                user = (User)realm.createObjectFromJson(User.class, profileResponse.toString());
            }catch (RealmException re){
                re.printStackTrace();
            }
            if(user != null) {
                Log.d(TAG, user.getFname()); //comes out correctly
                Log.d(TAG, user.getPlaces().size()) //always says 0
            }
            realm.commitTransaction();


        }

        @Override
        public void failure(RetrofitError error) {
            error.getCause();
        }
    });

知道为什么我在用户上调用 getPlaces 时什么都看不到吗?我尝试将领域对象嵌入领域对象中,看起来不错,只有领域列表似乎给我一个问题。我不确定在调用 createObject 时数据是否首先被保存到领域中。我也试过 createAllFromJson 但我得到了一个

Could not create JSON array from string

异常 编辑:示例 json {"places":[{"place_id":1280,"place_name":"加拿大"}}]}

【问题讨论】:

  • 你能在这里添加你的输入 JSON 吗?似乎它不是您要解析到领域的数组。应该是[{"name": "xxx"}]
  • 你的问题解决了吗?

标签: android realm realm-list


【解决方案1】:

我建议你使用 Gson 来处理 JSON。我已经通过以下实现成功地使用了 Gson、Retrofit 和 Realm。

  1. 使用排除策略构建 gson

    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;
                }
            })
    
  2. 将 Gson 添加到 RestAdapter 构建器

    RestAdapter.Builder()
            //.other settings
            .setConverter(new GsonConverter(gson))
            .build();
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多