swift4--解析json文件

首先添加一个供测试用的JSON文件

menu.json

{
	"menu":
	{
		"id": "file",
		"value": "File",
		"menuitem":
		[
			{
				"value": "New",
				"onclick": "CreateNewDoc()"
			},
			{
				"value": "OPen",
				"onclick": "OPenDoc()"
			},
			{
				"value": "Close",
				"onclick": "CloseDoc()"
			}
		]
	}
}

以下是解析过程

//解析json文档
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
//        从项目的目录结构中读取需要解析的文档
        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()
        // Dispose of any resources that can be recreated.
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_41735943/article/details/81270100