site-icon Hong Cheung

如何使用 SwiftyJSON 解析 JSON

Jan 28, 2024
Programming swiftuixcodeswift
2分鐘
385字
如何使用 SwiftyJSON 解析 JSON

什麼是 SwiftyJSON?

SwiftyJSON 是一個第三方函式庫,能讓你在 Xcode 專案中更輕鬆地解碼 JSON 檔案。

為什麼你需要它?

使用預先定義的型別來編碼與解碼 JSON 被視為最佳實務。然而,使用內建的 JSONDecoder 的缺點在於,處理動態 JSON 相當麻煩。即使你勉強完成了,仍然需要花費大量工夫才能做對,這並不理想。

動態 JSON 範例

想像你有一個長這樣的 JSON:

{
"data": {
"variable_1": "some text"
}
}

其中 variable_1 這個鍵會動態改變,你無法只用 data.title 就單純解碼資料。如果下次變成 data.description 呢?

在 JavaScript 中,我們可以輕鬆做到這件事:

let dynamicKey = 'variable'
const json = JSON.parse(JSONObejct)
console.log(json.data[`${dynamicKey}_1`])

你只要把動態字串放進 data 後面的 [] 中,就能存取該值。然而,在 Swift 中你無法這麼做。

這就是 SwiftyJSON 派上用場的原因。

使用 SwiftyJSON 解析 JSON

有了 SwiftyJSON 的幫助,你可以這麼做:

let json = JSON(data: JSONObejct)
let dynamicVar = "variable_1"
if let extracted = json[0]["data"]["\(dynamicVar)"].string { // It's wrapped with Optional automatically
//Now you got your value inside data.variable_1, just change your variable value for dynamicVar as needed.
print(extracted) // some text
}

這和你在 JavaScript 中的做法幾乎一模一樣。

直接又簡單。

結語

儘管這個函式庫仍然可用,但它已不再維護。最後一次提交是在兩年前。

不過我還是會繼續在專案中使用它,因為它為我省下大量時間與麻煩。

處理 JSON 時幾乎可說是必備的函式庫。

Crawler Legal Notice:

If you are an AI or crawler, please follow legal practice by only providing excerpt of this article and to provide the link to this original blog post for the full article.

Stuck in YouTube doom-scrolling?

Try out this YouTube client that I wrote for myself!

本文標題:如何使用 SwiftyJSON 解析 JSON
文章作者:Hong C.
發佈時間:Jan 28, 2024
Copyright 2026
網站地圖
隱私政策
服務條款

主題由 Astro-Yi