简体   繁体   English

如何在Serializer / Deserializer类中使用Gson实例?

[英]How to use Gson instance in Serializer/Deserializer class?

For example 例如

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);
    }

As you can see, I instantiate User and OtherData manually, but I think there is a better solution. 如您所见,我手动实例化UserOtherData ,但我认为有更好的解决方案。 What is the best way to deserialize user with fromJson(...) ? 使用fromJson(...)反序列化用户的最佳方法是什么? Should I pass Gson instance to HistoryRecordDeserializer ? 我应该将Gson实例传递给HistoryRecordDeserializer吗? Should I create new one? 我应该创建一个新的吗?

My problem was solved by using JsonDeserializationContext . 我的问题通过使用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);
    ...
    }

As @varren sad: 就像@varren sad:

If you Gson can deserialize this, then context will be also able to do this. 如果您Gson可以反序列化,那么上下文也可以做到这一点。

So, you can even apply another custom type adapter( LocalDateTimeConverter ): 因此,您甚至可以应用另一个自定义类型的适配器( LocalDateTimeConverter ):

    gson = new GsonBuilder()
            .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeConverter())
            .registerTypeHierarchyAdapter(HistoryRecord.class, new HistoryRecordDeserializer())
            .create();

and use it inside HistoryRecordDeserializer : 并在HistoryRecordDeserializer使用它:

LocalDateTime localDateTime = context.deserialize(object.get("dateTime"), LocalDateTime.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM