美文网首页
Swift 之读写 json 数据到文件

Swift 之读写 json 数据到文件

作者: willokyes | 来源:发表于2018-01-05 20:27 被阅读0次

    //
    let array = [
        ["clsName": "WBHomeViewController",
         "title": "首页",
         "imageName": "home",
         "visitorInfo": ["imageName": "",
                         "message": "关注一些人,回这里看看有什么惊喜"]],

        ["clsName": "WBMessageViewController",
         "title": "消息",
         "imageName": "message_center",
         "visitorInfo": ["imageName": "visitordiscover_image_message",
                         "message": "登录后,别人评论你的微博,给你发消息,都会在这里收到通知"]],

        ["clsName": "UIViewController"],

        ["clsName": "WBDiscoverViewController",
         "title": "发现",
         "imageName": "discover",
         "visitorInfo": ["imageName": "visitordiscover_image_message",
                         "message": "登录后,最新、最热微博尽在掌握,不再与实事潮流擦肩而过"]],

        ["clsName": "WBProfileViewController",
         "title": "我",
         "imageName": "profile",
         "visitorInfo": ["imageName": "visitordiscover_image_profile",
                         "message": "登录后,你的微博、相册、个人资料会显示在这里,展示给别人"]]
    ]

    // 写 json 方式一:
    let os = OutputStream(toFileAtPath: "/Users/willokyes/Desktop/main.json",
                          append: false)
    os?.open()
    JSONSerialization.writeJSONObject(array,
                                      to: os!,
                                      options: JSONSerialization.WritingOptions.prettyPrinted,
                                      error: NSErrorPointer.none)
    os?.close()
    
    // 写 json 方式二:
    let data = try! JSONSerialization.data(withJSONObject: array,
                                           options: JSONSerialization.WritingOptions.prettyPrinted)
    let url = URL(fileURLWithPath: "/Users/willokyes/Desktop/main.json")
    try! data.write(to: url, options: .atomic)
    
        
    // 读 json:main.json 已拖放至 Xcode 项目 Bundle 里
    guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
        let data = NSData(contentsOfFile: path),
        let array = try? JSONSerialization.jsonObject(with: data as Data) as? [[String: Any]]
    else {
        return
    }

相关文章

网友评论

      本文标题:Swift 之读写 json 数据到文件

      本文链接:https://www.haomeiwen.com/subject/gxasnxtx.html