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

I manually deserialize the User and OtherData objects. How can you do better? There is an idea to use an instance of Gson, passing it in the constructor, or create a new one in the HistoryRecordDeserializer . There are other options?

    2 answers 2

    Solved the problem using JsonDeserializationContext , which is passed as the argument to the JsonDeserializer.deserialize(...) method.

    For example:

     @Override public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); JsonObject extras = object.get("extraData").getAsJsonObject(); HistoryRecord hr = context.deserialize(object.get("data"), HistoryRecord.class); hr.appendExtraData(extras, HistoryRecordExtraData.class); ... } 

    In fact, the context is able to deserialize all the same as the instance of Gson . Passing a Gson instance is no longer necessary.

    Another example:

     UUID id = context.deserialize(object.get("id"), UUID.class); 

      If you use any DI-framework, you can inject it: @Inject (JavaEE or Guice) or @Autowired (Spring).

      Accordingly, in one place it will be possible to create a single instance of Gson , as well as control all its settings.