简体   繁体   中英

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. What is the best way to deserialize user with fromJson(...) ? Should I pass Gson instance to HistoryRecordDeserializer ? Should I create new one?

My problem was solved by using 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:

If you Gson can deserialize this, then context will be also able to do this.

So, you can even apply another custom type adapter( LocalDateTimeConverter ):

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

and use it inside HistoryRecordDeserializer :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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