我不想为json和realm创建单独的模型。我正在寻找一种方法。
如何在一个模型中处理而不创建两个模型?
我的杰森;
"story": {
"id": 3,
"title": "title",
"is_new": false,
"thumbnail": "url",
"original": "url",
}
MyRealmObject
public class stories extends RealmObject {
@PrimaryKey
@Required
private String id;
@Required
private String title;
private boolean isNew;
@Required
private String thumbnail;
@Required
private String original;
[..and getter setter..]
}
答案 0 :(得分:3)
您可以将相同的模型用于JSON解析和Realm。
您可能需要使用SerializedName
,因为字段is_new
无效。
示例:
public class Stories extend RealmObject {
private int id;
private String title;
@SerializedName("is_new") // required
private Boolean isNew;// use preferred name
private String thumbnail;
private String original;
/* getter & setter */
}
解析
Stories mDataClass = new Gson().fromJson("{/*whatever your json object*/}", Stories.class);