如何将Retrofit从NewsApi获取的3个POJO类转为RealmObject?
把Retrofit POJO转为RealmObject的详细步骤
嘿,我来帮你把这些Retrofit用的POJO改成RealmObject,操作其实很直观,咱们一步步来:
1. 先确认Realm依赖已配置(如果还没加的话)
首先得确保你的项目里已经引入了Realm的依赖,这一步如果已经搞定了可以直接跳过。
2. 修改每个POJO类为RealmObject
Realm要求实体类必须继承RealmObject,同时可以保留Retrofit的@SerializedName和@Expose注解(毕竟还要用Retrofit解析JSON)。另外要注意Realm不支持Object类型的字段,得把这类字段替换成Realm支持的类型(比如String、Integer等)。
修改后的Source类
import io.realm.RealmObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Source extends RealmObject { @SerializedName("id") @Expose private String id; // 把Object改成String,因为NewsApi的source id要么是字符串要么是null @SerializedName("name") @Expose private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
为啥把Object改成String?因为NewsApi返回的source id要么是字符串(比如"bbc-news")要么是null,用String完全能覆盖场景,而且Realm不支持Object这种泛型类型。
修改后的Article类(补全你没写完的常规字段示例)
import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; public class Article extends RealmObject { @SerializedName("source") @Expose private Source source; // 这里用上面修改后的RealmObject类型的Source @SerializedName("author") @Expose private String author; @SerializedName("title") @Expose private String title; @SerializedName("description") @Expose private String description; @PrimaryKey // 把url设为主键,因为每个文章的url是唯一的 @SerializedName("url") @Expose private String url; @SerializedName("urlToImage") @Expose private String urlToImage; @SerializedName("publishedAt") @Expose private Date publishedAt; // 建议把String转成Date,Realm支持Date类型,方便后续查询 @SerializedName("content") @Expose private String content; // 对应的getter和setter方法 public Source getSource() { return source; } public void setSource(Source source) { this.source = source; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } // 其他getter和setter和原来的逻辑一致,这里就不一一罗列了 }
3. 关键注意事项
- 保留Retrofit注解:
@SerializedName和@Expose一定要保留,这样Retrofit解析JSON的时候才不会出错,Realm不会影响这些注解的作用。 - 主键设置:给唯一字段加上
@PrimaryKey注解(比如Article的url),这样Realm可以避免重复存储相同的文章,还能提升查询效率。 - 类型兼容性:Realm支持的类型包括基本类型、String、Date、byte[],以及其他RealmObject子类,不要用Object、List以外的泛型集合(如果有列表的话要用
RealmList<Article>代替List<Article>)。 - 对象创建方式:之后创建这些实体类的对象时,不能直接用
new Article(),要通过Realm的API创建,比如realm.createObject(Article.class)或者realm.copyToRealm(article)(如果是从Retrofit解析来的对象,用copyToRealm把它复制到Realm数据库里)。
内容的提问来源于stack exchange,提问作者manwhotrycoding
相关产品推荐
相关产品推荐

