HelloCW
HelloCW

Reputation: 2355

How to desgin a class for json when I use Gson in Kotlin?

I'm a beginner of Json and Gson, I know I can map json into a class, and map a class to json via Gson.

"My Json" is a json data, I try to design a class "My Class" to map, but I think that "My Class" is not good. Could you show me some sample code? Thanks!

My Class

data class Setting (
        val _id: Long,  
        val Bluetooth_Stauts: Boolean,
        val WiFi_Name,String
        val WiFi_Statuse: Boolean
)

My Json

{
   "Setting": [

      {
        "id": "34345",
        "Bluetooth": { "Status": "ON" },
        "WiFi": { "Name": "MyConnect", "Status": "OFF"  }
      }
      ,

      {
         "id": "16454",
         "Bluetooth": { "Status": "OFF" }
      }

   ]

}

Updated

The following is made by Rivu Chakraborty's opinion, it can work well, but it's to complex, is there a simple way?

data class BluetoothDef(val Status:Boolean=false)

data class WiFiDef(val Name:String, val Status:Boolean=false)

data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
)

data class MDetailsList(val mListMetail: MutableList<MDetail>)


        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)    
        var aMDetailsList=MDetailsList(mListMetail)    
        val json = Gson().toJson(aMDetailsList)

Upvotes: 1

Views: 268

Answers (1)

Rivu Chakraborty
Rivu Chakraborty

Reputation: 1372

As per your JSON Structure, I think below class definition should work with Gson

data class Setting (
        val id: Long,  
        val Bluetooth: BluetoothDef,
        val WiFi:WiFiDef
)
data class BluetoothDef(val Status:String)
data class WiFiDef(val Name:String, val Status:String)

Explanation -

  • If you're getting an object in your JSON, you should define a class for that to use with Gson.
  • Data types should match, use String if you're getting Strings like "ON" and "OFF". You can use Boolean if you're getting true and false (without quotes).
  • The JSON Element name should match the variable/property name unless you're using @SerializedName to define JSON variable name while using different variable/property name.

*Note You can rename the classes if you want

I think it'll be helpful for you

Upvotes: 2

Related Questions