在这个问题解决之前,我已经在我的应用程序中做了一个变通方法,假设我已经
聊天.java
public class Chat extends RealmObject {
@Index
@SerializedName("c")
private String code = "";
@Index
@SerializedName("t")
private int type;
}
和RealmUtil.java
public class RealmUtil {
private static HashMap> classesFieldsMap = new HashMap<>();
static {
initClasses(Chat.class);
}
private static void initClasses(Class cls) {
if (!classesFieldsMap.containsKey(cls.toString())) {
Field[] fields = cls.getDeclaredFields();
HashMap fieldsMap = new HashMap<>();
for (Field a : fields) {
SerializedName annotation = a.getAnnotation(SerializedName.class);
if (annotation != null) {
fieldsMap.put(annotation.value(), a.getName());
}
}
classesFieldsMap.put(cls.toString(), fieldsMap);
}
}
public static JSONObject mapGsonObjectToRealm(Class cls, JSONObject object) throws JSONException {
JSONObject newUserObj = new JSONObject();
HashMap fieldsMap = classesFieldsMap.get(cls.toString());
for (String setKey : fieldsMap.keySet()) {
String mappedKey = fieldsMap.get(setKey);
if (object.has(setKey))
newUserObj.put(mappedKey, object.get(setKey));
}
return newUserObj;
}
}
通过使用反射initClasses方法,将类的每个Gson SerializedName映射到领域记录的相应名称。
mapGsonObjectToRealm方法将用新字段名创建旧对象的新对象。
用法:
JSONObject newObject = RealmUtil.mapGsonObjectToRealm(Chat.class, new JSONObject().put("c", "this_is_code").put("t", "this_is_type"));
final JSONArray jsonArray = new JSONArray();
jsonArray.put(newObject);
Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.createOrUpdateAllFromJson(Chat.class, jsonArray);
}
});