Tengo una clase Java POJO como esta:
class Topic { @SerializedName("id") long id; @SerializedName("name") String name; }y tengo una clase de datos de Kotlin como esta
data class Topic(val id: Long, val name: String) ¿Cómo proporcionar la json key a cualquier variable de la clase de kotlin data class como la anotación @SerializedName en variables java?
Clase de datos:
data class Topic( @SerializedName("id") val id: Long, @SerializedName("name") val name: String, @SerializedName("image") val image: String, @SerializedName("description") val description: String )a JSON:
val gson = Gson() val json = gson.toJson(topic)de JSON:
val json = getJson() val topic = gson.fromJson(json, Topic::class.java)Cree cualquier dato de clase y herede la interfaz JSONConvertable
interface JSONConvertable { fun toJSON(): String = Gson().toJson(this) } inline fun <reified T: JSONConvertable> String.toObject(): T = Gson().fromJson(this, T::class.java)clase de datos
data class User( @SerializedName("id") val id: Int, @SerializedName("email") val email: String, @SerializedName("authentication_token") val authenticationToken: String) : JSONConvertableDesde JSON
val json = "..." val object = json.toObject<User>()A JSON
val json = object.toJSON()Puedes usar similar en la clase Kotlin
class InventoryMoveRequest { @SerializedName("userEntryStartDate") @Expose var userEntryStartDate: String? = null @SerializedName("userEntryEndDate") @Expose var userEntryEndDate: String? = null @SerializedName("location") @Expose var location: Location? = null @SerializedName("containers") @Expose var containers: Containers? = null }Y también para la clase anidada puede usar lo mismo como si hubiera un objeto anidado. Simplemente proporcione el nombre de serialización para la clase.
@Entity(tableName = "location") class Location { @SerializedName("rows") var rows: List<Row>? = null @SerializedName("totalRows") var totalRows: Long? = null }por lo tanto, si obtiene una respuesta del servidor, cada clave se asignará a JOSN.
Alos, convierte List a JSON:
val gson = Gson() val json = gson.toJson(topic)Android convertir de JSON a objeto:
val json = getJson() val topic = gson.fromJson(json, Topic::class.java)