在iOS中找到JSON键名称或数据的方法有多种途径,以下是一些常用的方法:
示例代码:
struct MyDataModel: Codable {
let key1: String
let key2: Int
}
// 解析JSON数据
let jsonString = """
{
"key1": "value1",
"key2": 123
}
"""
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
do {
let dataModel = try decoder.decode(MyDataModel.self, from: jsonData)
print(dataModel.key1) // 输出:value1
print(dataModel.key2) // 输出:123
} catch {
print("解析JSON失败:\(error)")
}
示例代码:
let jsonString = """
{
"key1": "value1",
"key2": 123
}
"""
let jsonData = jsonString.data(using: .utf8)!
do {
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
if let jsonDict = jsonObject as? [String: Any] {
for (key, value) in jsonDict {
print("键名称:\(key)")
print("对应数据:\(value)")
}
}
} catch {
print("解析JSON失败:\(error)")
}
示例代码:
import SwiftyJSON
let jsonString = """
{
"key1": "value1",
"key2": 123
}
"""
let jsonData = jsonString.data(using: .utf8)!
let json = try! JSON(data: jsonData)
for (key, value) in json {
print("键名称:\(key)")
print("对应数据:\(value)")
}
以上是在iOS中找到JSON键名称或数据的几种常用方法,根据具体情况选择适合的方法进行使用。
领取专属 10元无门槛券
手把手带您无忧上云