0

I have next class structure:

class ExampleResponse(
    @SerializedName("status")
    val status: String
)

I am creating instance of this class via reflection:

fun convert(typeAdapterFactory: TypeAdapterFactory, gson: Gson): Optional<*> {
 return try {
            val genericTypeClassName = "com.example.package.ExampleResponse"
            val genericClass = Class.forName(genericTypeClassName)
            val genericTypeAdapter = gson.getDelegateAdapter(typeAdapterFactory, TypeToken.get(genericClass))
            val response = genericTypeAdapter.fromJson("{}")
            Optional.of(response)
        } catch (e: Exception) {
            Optional.empty<Any>()
        }
}

I am waiting that on the line genericTypeAdapter.fromJson("{}") it will throw exception, because status will be null. But I am receiving instance of ExampleResponse with null status field. I want to return Optional.empty() if status is null. How can I achieve this without checking fields? (checking field to non null is not acceptable because the real function is universal and I won't know what class I'll receive here).

Axbor Axrorov
  • 2,720
  • 2
  • 17
  • 35

1 Answers1

1

Gson doesn't know when a field can/cannot be null, since it's a Java library and Java knows nothing about nullability.

This question and answers suggests some workarounds: Gson optional and required fields

al3c
  • 1,392
  • 8
  • 15