2023年10月27日 星期五

【Android Studio】 Moshi 程式庫 : 將 JSON 字串轉換為 Kotlin 物件


新增 Moshi 程式庫依附元件

implementation 'com.squareup.moshi:moshi-kotlin:1.13.0'

實測另需添加以下 implementation ,才可以順利 import KotlinJsonAdapterFactory
implementation 'com.squareup.moshi:moshi-kotlin:1.14.0'

建立要轉換成的 Kotlin 物件類別( data class)

假設目標為此種格式的 JSON 字串:
[{
    "id":"424906",
    "img_src":"http://mars.jpl.nasa.gov/msl-raw-images/msss/01000/mcam/1000ML0044631300305227E03_DXXX.jpg"
},
...]

則建立 data class 如下:

data class MarsPhoto(
   val id: String, val img_src: String
)

Moshi 會自動比對 key 的名稱。
若想在 data class 中使用與 JSON key 給予的不同的名稱 (常見於 JSON檔案使用底線,但在 Kotlin 中想使用駝峰式大小寫的情況) ,則可以使用 JSON 註解。如下 :
data class MarsPhoto (
    val id: String, 
    @Json(name = "img_src") val imgSrcUrl: String
)

參考資料

0 comments:

張貼留言