Created
November 18, 2013 18:08
-
-
Save fab1an/7532478 to your computer and use it in GitHub Desktop.
Bug in GSON: DeserializationHandler changes Serialization of Abstract classes
This file contains 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
import static org.junit.Assert.*; | |
import java.lang.reflect.Type; | |
import org.junit.Test; | |
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.JsonParseException; | |
public class GsonSerializationTest { | |
@Test | |
public void test() { | |
GsonBuilder builder = new GsonBuilder(); | |
//builder.setPrettyPrinting(); | |
builder.registerTypeAdapter(AbstractClazz.class, new MetaDeserializer()); | |
Gson gson = builder.create(); | |
Container c = new Container(); | |
c.obj = new ConcreteClazz(); | |
String json = gson.toJson(c); | |
assertEquals("{\"obj\":{\"memberConcrete\":2,\"memberAbstract\":1}}", json); | |
} | |
private abstract static class AbstractClazz { | |
@SuppressWarnings("unused") | |
public int memberAbstract = 1; | |
} | |
private static final class ConcreteClazz extends AbstractClazz { | |
@SuppressWarnings("unused") | |
public int memberConcrete = 2; | |
} | |
private static final class Container { | |
@SuppressWarnings("unused") | |
public AbstractClazz obj; | |
} | |
private final class MetaDeserializer implements JsonDeserializer<Object> { | |
@Override | |
public Object deserialize(final JsonElement jsonElement, final Type type, | |
final JsonDeserializationContext jsonDeserializationContext) | |
throws JsonParseException | |
{ | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment