Home > Software design >  How to create universal model class for parsing Json with retorfit2?
How to create universal model class for parsing Json with retorfit2?

Time:09-21

All API response json structer is like: { "data":{ ... }, "meta":{ ... } }

But all API has different nested json inside data and meta. I need make universal parent json model class. This is my case:

class FirstJsonModel{
    
    @SerializedName("data")
    var data: FirstData? = null

    @SerializedName("meta")
    var meta: FirstMeta? = null
}

class FirstData {

}

class FirstMeta {

}


class SecondJsonModel {
    
    @SerializedName("data")
    var data: SecondData? = null

    @SerializedName("meta")
    var meta: SecondMeta? = null
}

class SecondData {

}

class SecondMeta {

}

CodePudding user response:

Use generic class

data class Hello<D,M>(
  @SerializedName("data")
  var data: D? = null,

  @SerializedName("meta")
  var meta: M? = null
)

CodePudding user response:

You can use a generic class to achieve this, considering the code you have shared -

class ApiResponseModel<T> {
     @SerializedName("data")
     var data: T? = null
}

OR

class ApiResponseModel<T1, T2> {
     @SerializedName("data")
     var data: T1? = null

     @SerializedName("meta")
     var meta: T2? = null
}

If you want to use is for Data Classes you can do something like this -

data class ApiResponseModel<T1, T2> (
     @SerializedName("data")
     var data: T1? = null,

     @SerializedName("meta")
     var meta: T2? = null
)

Hope this helps!

  • Related