Kotlin Data Class from Json using GSON

后端 未结 3 2018
梦毁少年i
梦毁少年i 2020-12-12 17:55

I have Java POJO class like this:

class Topic {
    @SerializedName(\"id\")
    long id;
    @SerializedName(\"name\")
    String name;
}

a

3条回答
  •  庸人自扰
    2020-12-12 18:32

    You can use similar in Kotlin class

    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
    }
    

    And also for nested class you can use same like if there is nested object. Just provide Serialize name for the Class.

    @Entity(tableName = "location")
    class Location {
    
        @SerializedName("rows")
        var rows: List? = null
        @SerializedName("totalRows")
        var totalRows: Long? = null
    
    }
    

    so if get response from the server each key will map with JOSN.

    Alos, convert List to JSON:

    val gson = Gson()
    val json = gson.toJson(topic)
    

    ndroid convert from JSON to Object:

    val json = getJson()
    val topic = gson.fromJson(json, Topic::class.java)
    

提交回复
热议问题