[英]String convert to Json Array and then parse value in swift iOS?
我是 swift 語言的新手。 我正在嘗試從 API 調用中獲取一些數據,並響應 API 為“{“status”:1,“msg”:“請輸入手機號碼”}”
我在字符串中有上述響應如何將此字符串轉換為 JSONObject,然后對其進行解析並獲取狀態值?
我是 android 開發人員,我們在調試代碼時評估表達式是否有一些類似於 Xcode 的代碼,所以我可以執行一些代碼運行時間
我建議使用SwiftyJson
庫。 首先使用http://jsoncafe.com
您可以使用以下代碼解析數據和 model
let json = JSON(response)
let message = Message(fromJson: json )
然后你可以訪問你的變量 => message.status
JSONSerialization
是您正在尋找的工具。 它處理將 JSON 轉換為對象,並將對象轉換為 JSON。 如果您收到表示為Data
的 JSON 字符串,則可以將其傳遞給JSONSerialization.jsonObject(with:options:)
如果您想將Data
轉換為 object:
//Where 'data' is the data received from the API call
guard let jsonObject = try? (JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]) else {
return
}
let status = jsonObject["status"] as! Int
let message = jsonObject["msg"] as! String
如果您想將String
轉換為 object:
//Where 'string' is the JSON as a String
guard let jsonObject = try? (JSONSerialization.jsonObject(with: string.data(using: .utf8), options: []) as! [String:Any]) else {
return
}
let status = jsonObject["status"] as! Int
let message = jsonObject["msg"] as! String
來源: https://developer.apple.com/documentation/foundation/jsonserialization
創建 model 並使用可解碼協議
例子:-
import Foundation
let json = """
{"status":1,"msg":"Please enter Mobile number"}
""".data(using: .utf8)!
struct Model: Codable {
let status: Int
let msg: String
}
let decoder = JSONDecoder()
let modelData = try! decoder.decode(Model.self, from: json)
print(modelData.status)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.