如何在Moshi中使用RealmObject [英] How to use a RealmObject with Moshi

查看:113
本文介绍了如何在Moshi中使用RealmObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为User的自定义对象,它是一个RealmObject.该对象还具有Moshi的注释,因为我计划在改造调用中使用该对象.

I have a custom object named User, which is a RealmObject. This object also has annotations for Moshi because I plan on using this object in a retrofit call.

public class User extends RealmObject
{
    @PrimaryKey private long id;
    @Json(name = "email") private String email;
    @Json(name = "first_name") private String firstName;
    @Json(name = "last_name") private String lastName;
    @Json(name = "password_hash") private String passwordHash;
    @Json(name = "avatar") private String avatar;
    @Json(name = "phone_number") private String phoneNumber;
    @Json(name = "country") private String country;
    @Json(name = "city") private String city;
    @Json(name = "address") private String address;
    @Json(name = "location") private Location location;
    @Json(name = "zip") private String zip;
    @Json(name = "device_meta") private DeviceMeta deviceMeta;
}

当我在Realm数据库中查询这样的用户时:

When I query my Realm DB for a user like this:

User user = getRealm().where(User.class).findFirst();

我收到此响应(使用调试):

I get this response (using debugging):

可以看出,该对象未初始化,但值显示在第一行.

As can be seen, the object isn't initialized but the values are showing in the first line.

这是什么问题?

当我将上述对象作为@Body参数传递时,它似乎为空.

When I pass the above object as a @Body parameter, it appears to be empty.

我还通过Fiddler进行了检查,并且发送到服务器的请求包含一个空对象.

I've also checked via Fiddler and the request sent to the server contains an empty object.

问题:如何获取此对象以获取正确的值?

Question: How do I get this object to get the proper values?

推荐答案

假设您正确保存和查询,它可能具有正确的值. Realm将每个扩展RealmObject的子类版本创建为"RealmProxy"对象,有时在调试器中它看起来不像您期望的那样.您会注意到您的类实际上显示为UserRealmProxy(但是在User = ...之后,它的内联值不为null).

It likely has the proper values assuming you're saving and querying correctly. Realm creates a subclassed version of each extended RealmObject as a "RealmProxy" object, and sometimes the in the debugger it doesn't look like what you would expect. You'll notice that your class is actually showing up as UserRealmProxy (but it's inline values aren't null after User = ...).

要查看非域代理版本,您必须使用Realm.copyFromRealm(...).

To view the non-realm proxy version, you would have to use Realm.copyFromRealm(...).

此外,请注意,从网络解析的任何内容都不会自动添加到Realm -在这种情况下,您必须显式复制到Realm才能获取后续查询的值,因为最初从网络解析的内容是不受管理的

Also, note that anything parsed from the network won't be added to Realm automatically -- you have to explicitly copy to realm in this case to get the values on later queries, since things parsed in from the network are unmanaged initially.

这篇关于如何在Moshi中使用RealmObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆