0

所以我开始使用 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":"Canada"}}]}

4

1 回答 1

0

I suggest you to use Gson to deal with JSON. I have successfully used Gson, Retrofit and Realm with following implementation.

  1. Build gson with exclusion strategy

    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. Add Gson to RestAdapter builder

    RestAdapter.Builder()
            //.other settings
            .setConverter(new GsonConverter(gson))
            .build();
    
于 2015-07-25T13:41:23.343 回答