Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
NSJSONSerialization.dataWithJSONObject崩溃_Json_Xcode_Swift_Ios8 - Fatal编程技术网

NSJSONSerialization.dataWithJSONObject崩溃

NSJSONSerialization.dataWithJSONObject崩溃,json,xcode,swift,ios8,Json,Xcode,Swift,Ios8,我对nsjsonserialization.dataWithJSONObject有问题 这将使我的应用程序崩溃: @IBAction func sendMessage(sender: AnyObject) { cachedMessage = messageField.text messageField.text = "" let messageData = NSJSONSerialization.dataWithJSONObject(cachedMessage, op

我对nsjsonserialization.dataWithJSONObject有问题

这将使我的应用程序崩溃:

@IBAction func sendMessage(sender: AnyObject) {

    cachedMessage = messageField.text
    messageField.text = ""

    let messageData = NSJSONSerialization.dataWithJSONObject(cachedMessage, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

...

}

我希望您能以某种方式帮助我…

它会给您一个错误,如:JSON写入中的顶级类型无效

如果您试图创建JSON对象,那么它应该来自数组或字典因为要转换为JSON的对象必须是顶级对象。

顶级对象是NSArray或NSDictionary

    let msgDataOfArray = NSJSONSerialization.dataWithJSONObject(demoArray, options: NSJSONWritingOptions.PrettyPrinted, error:nil)
    let msgDataOfDic = NSJSONSerialization.dataWithJSONObject(demoDic, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
试着这样做:

    var demoArray : NSArray! // (Use it if you want to send data as an Array)
    var demoDic : NSDictionary! // (Use it if you want to send data as an Dictionary (Key - Value Pair))

    var cachedMessage : String! 
    cachedMessage = "Sample" // Here your String From textfield

    demoArray = [cachedMessage] // Array with your string object
    demoDic = ["Your Key":cachedMessage] // Dic with your string object. 
您可以提供所需的密钥,而不是您的密钥

这就是如何从数组和字典创建数据

    let msgDataOfArray = NSJSONSerialization.dataWithJSONObject(demoArray, options: NSJSONWritingOptions.PrettyPrinted, error:nil)
    let msgDataOfDic = NSJSONSerialization.dataWithJSONObject(demoDic, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
若你们想看看你们的数据在JSONSerialization过程后会是什么样子的,那个么你们可以像下面这样看

    var DataToStringForArray = NSString(data: msgDataOfArray!, encoding: NSUTF8StringEncoding)
    var DataToStringForDic = NSString(data: msgDataOfDic!, encoding: NSUTF8StringEncoding)

    println("Data To String OF Array : \(DataToStringForArray)")
    println("Data To String OF Dic : \(DataToStringForDic)")