根据此SerializeToJson.java,尝试使用Gson从领域对象创建json字符串。而且它过去在4.0境界上可以正常工作,但在5.8.0境界下却无法正常工作。获取java.lang.ClassNotFoundException: io.realm.LevelRealmProxy
我是否缺少某些东西?无论如何,这是我的代码:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
setUpRealm();
checkProxy();
}
private void setUpRealm() {
Realm.init(this);
}
private void checkProxy() {
Realm realm = null;
try {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(Class.forName("io.realm.LevelRealmProxy"), new LevelSerializer())
.create();
// Serialize a Realm object to a JSON string
realm = Realm.getDefaultInstance();
Log.d("MyLogs", gson.toJson(realm.where(Level.class).findFirst()));
} catch (ClassNotFoundException e) {
Log.e("MyLogs", e.toString());
e.printStackTrace();
} finally {
if (realm != null) realm.close();
}
}
RealmObject
public class Level extends RealmObject {
String id;
int order;
}
TopLevel Gradle
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath "io.realm:realm-gradle-plugin:5.8.0"
}
应用程序级别gradle
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
android {
compileSdkVersion 28
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
我发现了解决方法,对RealmObject使用copyFromRealm()
而不对Gson使用registerTypeAdapter
答案 0 :(得分:1)
从Realm 5.0.0开始,代理类包含FQN作为RealmProxy的前缀,而不仅仅是类的简单名称。因此io.realm.LevelRealmProxy
现在是io.realm.yourpackage_to_the_realmobject_LevelRealmProxy
(为了在不同的程序包中支持多个具有相同名称的RealmObject)。