Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

355
Vistas
Gson: Derserialize a dynamic field

I'm using a very strange api, it's data field type is dynamic.
If error occured, the data field will be a string like this:

{
  "code": 2001,
  "data": "Error!"
}

And if success, the data field will be a object:

{
  "code": 2000,
  "data": {
    "id": 1,
    "name": "example"
  }
}

I'm using the following Kotlin code to de-serialize it:

return Gson().fromJson(data, SimpleModel::class.java)

The model definition is down below:

import com.google.gson.annotations.SerializedName

class SimpleModel {
    @SerializedName("code")
    val code = 0

    @SerializedName("data")
    val data: SimpleData = SimpleData()
}

class SimpleData {
    @SerializedName("id")
    val id = ""

    @SerializedName("name")
    val name = ""
}

When no error occred, the code above works just fine. However when error occured, exception was thrown:

java.lang.IllegalStateException: Excepted BEGIN_OBJECT but was STRING at line 1 column x $path.data

Is there a way to de-serialize data field to an object or just anything and determine it's type by code manually?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You would need to write a custom deserializer, which decides what type to deserialize data into, depending on the runtime type of the node, and register that deserializer with your Gson instance. Unfortunately i am not familiar with kotlin syntax, so i can only give you pseudo code.

  1. Field data in SimpleModel should be either Object, or make the class generic - SimpleModel<T>, and the field should be of type T as well.
  2. Parse the input to gson's node type - JsonElement.
  3. Get data field
JsonElement root = parseResponse();
root.getAsJsonObject().get("data").getAsString();
  1. Use getAs...() methods to check type.
  2. Get as string. If success, it's a string and set the string value in SimpleModel.
  3. If you get exception getting as string, get it as object - getAsJsonObject(), parse the object to SimpleData and set this new object in SimpleModel.

You could use my my answer here as inspiration. Although it's about object mapper, it does the same thing - decides object type depending on the node type, and follows roughly the same algorithm i described above.

Also this guide has info about how to write yor own deserialzer and registering it.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda