首先添加一个供测试用的JSON文件
menu.json
{
"menu":
{
"id": "file",
"value": "File",
"menuitem":
[
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "OPen",
"onclick": "OPenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
以下是解析过程
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "menu", ofType: "json")
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path!)) {
do{
if let jsonObj:NSDictionary = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions()) as? NSDictionary
{
if let menuDic:NSDictionary = jsonObj["menu"] as? NSDictionary
{
if let menuItems:NSArray = menuDic["menuitem"] as? NSArray
{
for item in menuItems{
print("item: \(item)")
}
}
}
}
} catch{
print("Error.")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}