我创建了扩展RealmObject的类。 并计划添加Map
字段如下,但我注意到Realm不支持Map
呢。具有映射字段的Java RealmObject
public class SmsPattern extends RealmObject {
@PrimaryKey
private String id;
@Required
private String address;
@Required
private String regex;
@Required
private Map<Integer, Integer> regexGroup;
}
所以作为替代,我将其转换Map
到Json String
和使用Json String
代替Map
这样。
public class SmsPattern extends RealmObject {
@PrimaryKey
private String id;
@Required
private String address;
@Required
private String regex;
@Required
private String regexGroup;
@Ignore
private Map<Integer, Integer> regexGroupMap;
public Map<Integer, Integer> getRegexGroupMap() {
Type type = new TypeToken<Map<Integer, Integer>>(){}.getType();
return new Gson().fromJson(getRegexGroup(), type);
}
public void setRegexGroupMap(Map<Integer, Integer> regexGroupMap) {
setRegexGroup(new Gson().toJson(regexGroupMap));
}
}
这是一个正常的解决方案吗? 还是更好的主意?
不好意思捎带你的问题。我使用realm 1.1.0,它修复了几个问题,但是我看到一个奇怪的行为,我将值放入我的唯一键控的RealmObject中的(At)Ignore Map字段中,但是当我查询该对象时Map是空的。我想我理解这是为什么(因为(在)忽略字段没有持久性?),但是如何在RealmObject中有任何(at)Ignore字段是有用的?很显然,我必须错过这里明显的东西...... – swooby