SkipWrongTypeAdapterFactory – Prevent Gson Crashes from Type Mismatches
An open-source Kotlin utility to gracefully handle JSON parsing errors due to incorrect data types

Introduction
SkipWrongTypeAdapterFactory is a class in Kotlin that provides a way to ignore errors found in JSON parsing due to wrong data types. It is particularly useful when dealing with external APIs that may return unexpected data types.
Features
Error Tolerance – Ignores JSON parsing errors caused by incorrect data types, preventing application crashes.
Seamless Integration – Easily integrates with existing Gson configurations by registering as a TypeAdapterFactory
.
Data Consistency – Ensures that the parsing process continues smoothly, setting fields with incorrect data types to null
or default values.
Lightweight and Efficient – Designed for optimal performance with minimal overhead.
Help to Avoid
If response of the API doesn’t come as expected object, then the Gson Builder throw the following exception:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 57 path $.data.firstName
Logs of Exception

How to use
To use this class, simply create an instance of it and register it with your Gson instance:
val gson = GsonBuilder()
.registerTypeAdapterFactory(SkipWrongTypeAdapterFactory())
.create()
Example
@Provides
@Singleton
fun provideGson(): Gson {
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
.setPrettyPrinting()
.setLenient()
if (!BuildConfig.DEBUG) {
gson.registerTypeAdapterFactory(SkipWrongTypeAdapterFactory())
}
return gson.create()
}
How it works
Suppose you have the following JSON:
{
"name": "John",
"age": "30"
}
If you try to deserialize this JSON into a class with an integer age field, you will get a JsonSyntaxException due to the age field being a string. However, if you use SkipWrongTypeAdapterFactory, the exception will be ignored and the age field will be set to null.
data class Person(val name: String, val age: Int)
val gson = GsonBuilder()
.registerTypeAdapterFactory(SkipWrongTypeAdapterFactory())
.create()
val json = "{\"name\": \"John\", \"age\": \"30\"}"
val person = gson.fromJson(json, Person::class.java)
println(person.age) // prints "null"
Crafted In
Let’s Improve Together
Your reactions guide development. Please share your thoughts on new features or recommendations. Unitedly we can improve to help all.