使用GSON反序列化包含其他Realm对象的Realm对象?

时间:2017-03-21 10:57:36

标签: android gson realm

我有一个实体,员工:

public class Employee extends RealmObject implements Serializable {
    @PrimaryKey
    @SerializedName("id") public long id;

    @SerializedName("name") public String firstName;
    @SerializedName("lastName") public String lastName;
    @SerializedName("profilePictureSmall") public String profilePictureSmallUrl;
    @SerializedName("contact") public Contact contact;
}

public class Contact extends RealmObject implements Serializable {
    @PrimaryKey
    @SerializedName("id") public long id;

    @SerializedName("workMail") public String workEmail;
    ... Some other fields ...
}

从json反序列化Employee时,所有String字段和long字段都会被正确反序列化,但我的contact字段会保留null

我尝试为Employee编写自定义反序列化器:

public class DeserializeEmployee implements JsonDeserializer<Employee> {
    @Override
    public Employee deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Log.d(TAG, "Deserializing Employee");
        Employee employee = new Employee();
        JsonObject o = json.getAsJsonObject();
        employee.id = o.get("id").getAsLong();
        employee.firstName = o.get("name").getAsString();
        employee.lastName = o.get("lastName").getAsString();
        employee.profilePictureSmallUrl = o.get("profilePictureSmall").getAsString();
        employee.contact = context.deserialize(o.get("contact"), Contact.class);
        return employee;
    }
}

和联系人的自定义反序列化器:

public class DeserializeContact implements JsonDeserializer<Contact> {
    @Override
    public Contact deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Log.d(TAG, "Deserializing Contact");
        Contact contact = new Contact();
        JsonObject o = json.getAsJsonObject();
        contact.id = o.get("id").getAsLong();
        contact.workEmail = o.get("workMail").getAsString();
        return contact;
    }
}

我也注册了他们:

Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime()))
                .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
                .registerTypeAdapter(Contact.class, new DeserializeContact())
                .registerTypeAdapter(Employee.class, new DeserializeEmployee())
                .create();

调用我的Employee反序列化器并正确设置其原始字段,但我的联系反序列化器根本没有被调用,因此字段contactnull

JSON:

{
  "id": 5,
  "name": "John",
  "lastName": "Doe",
  "profilePictureSmall": "http://example.com/fjlsjf",
  "contact": {
     "id": 9,
     "workMail": "johndoe@gmail.com"
  }
}

编辑如果有人需要,可以添加示例json,但很确定它不是问题所在。

2 个答案:

答案 0 :(得分:1)

我从服务器发送了错误的JSON,其中不包含contact字段。当我实际发送了适当的数据时,一切都有效,即使没有自定义反序列化器。很抱歉浪费每个人的时间。

答案 1 :(得分:0)

尝试这样做:

employeeObject = realm.copyFromRealm(employeeObject);