Created
November 19, 2025 13:32
-
-
Save Nikos410/4edb3f1f0f22dc10914e928ea1bd0edb to your computer and use it in GitHub Desktop.
gson TypeAdapter that delegates to Jackson ObjectMapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package de.nikos410; | |
| import java.lang.reflect.Type; | |
| import com.fasterxml.jackson.core.JsonProcessingException; | |
| import com.fasterxml.jackson.databind.ObjectMapper; | |
| import com.google.gson.Gson; | |
| import com.google.gson.GsonBuilder; | |
| import com.google.gson.JsonDeserializationContext; | |
| import com.google.gson.JsonDeserializer; | |
| import com.google.gson.JsonElement; | |
| import com.google.gson.JsonObject; | |
| import com.google.gson.JsonParseException; | |
| import com.google.gson.JsonSerializationContext; | |
| import com.google.gson.JsonSerializer; | |
| /** | |
| * Use it like this: | |
| * | |
| * <pre> | |
| * gsonBuilder.registerTypeAdapter(MyType.class, | |
| * new de.nikos410.JacksonGsonTypeAdapter<>( | |
| * jacksonObjectMapper, MyType.class)); | |
| * </pre> | |
| */ | |
| public class JacksonGsonTypeAdapter<T> | |
| implements JsonSerializer<T>, JsonDeserializer<T> { | |
| private final ObjectMapper jacksonObjectMapper; | |
| private final Class<T> typeClass; | |
| private final Gson gson; | |
| private JacksonGsonTypeAdapter(ObjectMapper jacksonObjectMapper, | |
| Class<T> typeClass) { | |
| this.jacksonObjectMapper = jacksonObjectMapper; | |
| this.typeClass = typeClass; | |
| this.gson = new GsonBuilder().create(); | |
| } | |
| @Override | |
| public JsonElement serialize(T dto, Type typeOfSrc, | |
| JsonSerializationContext context) { | |
| try { | |
| final String valueAsString = | |
| jacksonObjectMapper.writeValueAsString(dto); | |
| return gson.fromJson(valueAsString, JsonObject.class); | |
| } catch (JsonProcessingException e) { | |
| throw new IllegalStateException("Could not serialize " + dto, e); | |
| } | |
| } | |
| @Override | |
| public T deserialize(JsonElement json, Type typeOfT, | |
| JsonDeserializationContext context) throws JsonParseException { | |
| try { | |
| final String valueAsString = gson.toJson(json); | |
| return jacksonObjectMapper.readValue(valueAsString, typeClass); | |
| } catch (JsonProcessingException e) { | |
| throw new JsonParseException(e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment