合并域对象和放大器; GSON对象对象、放大器、GSON

2023-09-06 02:00:49 作者:心已倦

我的目标是为坚持一个实例化GSON同领域中的数据库对象

我的问题是这样的:

我可以实例化一个对象GSON,所以GSON通吃的特性照顾, 但它不会被持久化到数据库

I can instantiate an object with GSON, so GSON takes care of all the properties, but then it won't be persisted to db

我可以实例化一个对象境界,但我必须填写所有的setter方法​​的属性。

I can instantiate an object with Realm, but then I have to fill in all the setters for the properties.

在我的OnCreate,这部分是相同的两种方法

In my oncreate, this part is the same for both methods

//delete previous realm file
Realm.deleteRealmFile(this);

//gson instance
Gson gson = new Gson();

//realm instance
realm = Realm.getInstance(this);

**我的类的名字是Vacature **

** The name of my class is Vacature **

信息:我知道下面的code需要在里面:

Info: I am aware that the following code needs to be inside:

realm.beginTransaction();

// code here

realm.commitTransaction();

选项1:

//get class with gson
Vacature vacatureGson = gson.fromJson(jsonString, Vacature.class);

这是行不通的,因为你必须通过实例化一个领域对象

This won't work because you have to instantiate a realm object by using

Class instance = realm.createObject(Class.class); // Create a new object

选项2:

//get instance with gson
Vacature vacatureGson = gson.fromJson(jsonString, Vacature.class);
//make instance with realm
Vacature realmVacature = realm.createObject(Vacature.class);
realmVacature = vacatureGson;

这是行不通的,因为这不是复制所有属性从一个对象到另一个有道。 如果有然而从gsonObject所有属性复制到realmObject的好方法, 选项​​2可能会奏效。

This won't work because this is not a proper way to copy all the properties from one object to another. If there is however a good way to copy all the properties from the gsonObject to the realmObject, option 2 might work.

在如何解决这一难题的任何想法?

Any ideas on how to solve this puzzle?

推荐答案

从埃马努埃莱境界这里。

Emanuele from Realm here.

现在的解决方案是次优的,是psented中的一个例子$ P $:https://github.com/realm/realm-java/blob/master/examples/gridViewExample/src/main/java/io/realm/examples/realmgridview/GridViewExampleActivity.java

Right now the solution is suboptimal and is presented in one of the examples: https://github.com/realm/realm-java/blob/master/examples/gridViewExample/src/main/java/io/realm/examples/realmgridview/GridViewExampleActivity.java

我们正努力使经验的方式顺畅!

We're working to make the experience way smoother!