如何序列化包含NSDictionaries的{NSDictionary

时间:2017-05-01 13:49:23

标签: ios json swift

我正在尝试序列化包含NSDictionaries数组的NSDictionary并将其保存到文件中。我的代码如下(船只是NSDictionaries的数组,gameOver,暂停和级别只是布尔值或整数;每个船只字典只是由原始类型(没有嵌套字典)形成)

private var dictionaryRepresentation: NSDictionary { 
        var ships: [NSDictionary] = []
        for ship in mShips {
            ships.append(ship.convertToDictionary())
        }
        return ["gameOver": gameOver, "paused": paused, "level": level, "ships": ships]
    }

public func save() {
        // Save JSON to file
        var pathURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last
        pathURL = pathURL?.appendingPathComponent("jsoncontent.json")
        let contentDictionary: NSDictionary = dictionaryRepresentation

        let jsonData = try! JSONSerialization.data(withJSONObject: gameDictionary, options: .prettyPrinted)
        try! jsonData.write(to: pathURL!)
    }

我在行

中遇到异常
let jsonData = try! JSONSerialization.data(withJSONObject: gameDictionary, options: .prettyPrinted)

如果我删除了船舶的键值,它可以正常工作。 什么是错误的或其他方法呢?

0 个答案:

没有答案