package data; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import java.lang.reflect.Type; /** * Validates the deserialization of a JSON string. The main motivation of this * class is to print the property name of an object that throws an * IllegalStateException because a string was expected, but a different type got * returned. * * @author Peter Wu */ public class DebuggingJsonDeserializer extends ValidatingJsonDeserializer { private final Class overriddenClass; private DebuggingJsonDeserializer(Class overriddenClass) { this.overriddenClass = overriddenClass; } @Override public Object deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { checkObject("", je, overriddenClass); return null; } public static void tryValidate(String json, Class cls) { new GsonBuilder() .registerTypeAdapter(Dummy.class, new DebuggingJsonDeserializer(cls)) .create() .fromJson(json, Dummy.class); } private class Dummy { } }