例如
public class HistoryRecordDeserializer implements JsonDeserializer<HistoryRecord> {
private LocalDateTimeConverter dateTimeConverter = new LocalDateTimeConverter();
@Override
public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
User user = new User();
user.setId(UUUID.fromString(json.get("user").get("id").getAsString()));
OtherData data = new OtherData();
data.setData(json.get("otherData").getAsLong());
return UserAndData(user, otherData);
}
如您所见,我手动实例化User
和OtherData
,但我认为有更好的解决方案。使用fromJson(...)
反序列化用户的最佳方法是什么?我应该将Gson实例传递给HistoryRecordDeserializer
吗?我应该创建新的吗?
答案 0 :(得分:0)
使用JsonDeserializationContext
解决了我的问题。
@Override
public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
JsonObject extras = object.get("extraData").getAsJsonObject();
HistoryRecord hr = object.context.deserialize(object.get("data"), HistoryRecord.class);
hr.appendExtraData(extras, HistoryRecordExtraData.class);
...
}
@varren悲伤:
如果Gson可以反序列化,那么上下文也可以这样做。
因此,您甚至可以应用其他自定义类型适配器(LocalDateTimeConverter
):
gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeConverter())
.registerTypeHierarchyAdapter(HistoryRecord.class, new HistoryRecordDeserializer())
.create();
并在HistoryRecordDeserializer
内使用
LocalDateTime localDateTime = context.deserialize(object.get("dateTime"), LocalDateTime.class);