我有一个实体,员工:使用GSON反序列化包含其他Realm对象的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
。
我试着写了员工的自定义解串器:
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();
我的员工反序列化器被调用,它的原始字段设置正确,但我的联系解串器isn根本不叫,而contact
因此是null
。
JSON:
如果有人需要{
"id": 5,
"name": "John",
"lastName": "Doe",
"profilePictureSmall": "http://example.com/fjlsjf",
"contact": {
"id": 9,
"workMail": "[email protected]"
}
}
编辑新增样本JSON,但可以肯定是没问题的。
你有这个json的计划吗? – ste9206
@ ste9206添加了示例json。 –
@MarkoStojanovic只是好奇:为什么你需要定制(de)序列化器? Gson可以以更高的效率开箱即用(它在类型适配器中使用流式传输,而不是在(de)序列化器中使用的全内存JSON树)。 +请注意,使用自定义(de)序列化程序将禁用内置类型适配器,因此您的“@ SerializedName”注释不起作用。 –