Swift 之读写 json 数据到文件


    //
    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
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容