NSJSONSeralization.dataWithJSONObject崩溃

时间:2014-11-03 10:03:48

标签: json xcode swift ios8

我遇到了NSJSONSeralization.dataWithJSONObject。

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

@IBAction func sendMessage(sender: AnyObject) {

    cachedMessage = messageField.text
    messageField.text = ""

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

...

}

我希望你能以某种方式帮助我...

1 个答案:

答案 0 :(得分:1)

它会出现如下错误: JSON写入中的顶级类型无效

如果您正在尝试创建JSON对象,那么它应该来自Array或Dictionary。 因为要转换为JSON的对象必须是顶级对象。

  

顶级对象是NSArray或NSDictionary。

尝试这种方式:

    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)")