I get a json that has \"field\" field.
If the \"field\" has data, then there is an OBJECT that has many (about 20) other fields that are also objects. I can deserialize
I created an alternative TypeAdapter based on my needs to let empty arrays deserialize to null, but only for the classes I specify:
class EmptyArraysAsNullTypeAdapterFactory @Inject constructor() : TypeAdapterFactory {
companion object {
// Add classes here as needed
private val classesAllowedEmptyArrayAsNull = arrayOf(Location::class.java,
Results::class.java)
private fun isAllowedClass(rawType: Class<*>): Boolean {
return classesAllowedEmptyArrayAsNull.find { rawType.isAssignableFrom(it) } != null
}
}
override fun create(gson: Gson, type: TypeToken): TypeAdapter? {
val delegate = gson.getDelegateAdapter(this, type)
val rawType = type.rawType as Class
return object : TypeAdapter() {
override fun write(out: JsonWriter, value: T?) {
delegate.write(out, value)
}
override fun read(reader: JsonReader): T? {
return if (reader.peek() === JsonToken.BEGIN_ARRAY && isAllowedClass(rawType)) {
reader.beginArray()
// If the array is empty, assume it is signifying null
if (!reader.hasNext()) {
reader.endArray()
null
} else {
throw JsonParseException("Not expecting a non-empty array when deserializing: ${type.rawType.name}")
}
} else {
delegate.read(reader)
}
}
}
}
}