swift读取json
时间: 2023-08-29 13:11:03 浏览: 124
Parsing JSON in Swift
在Swift中读取JSON数据可以使用NSJSONSerialization类。您可以使用以下代码示例来读取JSON数据:
```swift
// 从一个本地项目资源中读取data.json文件
if let path = NSBundle.mainBundle().pathForResource("data", ofType: "json") {
if let nsUrl = NSURL(fileURLWithPath: path) {
if let nsData = NSData(contentsOfURL: nsUrl) {
// 读取JSON数据
if let json = try? NSJSONSerialization.JSONObjectWithData(nsData, options: []) {
// 读取普通数据
if let id = json["id"] as? String {
print(id)
}
// 读取数组类型数据
if let array = json["data"] as? [String {
print(array.count)
}
}
}
}
}
```
以上代码将从本地项目资源中读取一个名为data.json的文件,并解析其中的JSON数据。您可以通过键来访问JSON中的数据,并将其转换为适当的类型。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [在Swift中使用JSON](https://blog.csdn.net/cunjie3951/article/details/106922527)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Swift 读取,处理Json数据](https://blog.csdn.net/Riven_wn/article/details/51744646)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文