yams
yams

Reputation: 952

Androidx Kotlin using Gson, needing to created a nested GSON data class

I've got an android app using kotlin, and I'm also using the gson google library. What I'm trying to do is create a nested data class to match the json object I'm getting back. JSON :

{
  "results":{
    "userid": "575",
    "email" : "joe@joe"
   },
   "errors": {"errormessage":"no errors found"}
}

I am creating a kotlin data class using GSON but I am not sure how to handle the nested portions so that the GSON object would match the json above Below is what I think would work.

Upvotes: 0

Views: 735

Answers (2)

Mahdi Rajabi
Mahdi Rajabi

Reputation: 602

Since you need all data being in same data class, you need first flatten the json using utilities like json-flattener which is available in following link: The author has described how to use the library.

Json-Flattener

This utility will convert you hierarchical json object to flat format like:

{
    "results.userid": "575",
    "results.email": "joe@joe",
    "errors.errormessage": "no errors found"
}

Then you can deserialize it to the data class model like:

data class Response(
    @SerializedName("results.userid") val userId: String?,
    @SerializedName("results.email") val email: String?,
    @SerializedName("errors.errormessage") val errorMessage: String?
)

Upvotes: 1

Lena Bru
Lena Bru

Reputation: 13947

data class Response( @SerializedName("results") val results: Results? = null, @SerializedName("errors") val errors: Errors? = null)

data class Results(@SerializedName("userid") val userId: String, @SerializedName("email") val email:String)

data class Errors(@SerializedName("errormessage") val errorMessage:String)

Upvotes: 2

Related Questions