iOS Swift给出错误:从json序列化数据时结束垃圾

时间:2016-05-17 18:40:08

标签: ios json swift

我要解析以下json。但是当序列化函数运行时会抛出错误

  

错误Domain = NSCocoaErrorDomain Code = 3840“垃圾结束”。

{
    "b_categories": [{
        "id": "20",
        "english": "GameCon",
        "translitation": "06af06cc064506a906480646",
        "urdu": "06af06cc064506a906480646",
        "audio": "0863.ogg",
        "file_type": "audio/ogg",
        "file_size": "67.251",
        "file_name": "1462621581.ogg",
        "temp_name": "/tmp/phpisH1mM",
        "listing_a_id": "9",
        "status": "1"
    }, {
        "id": "19",
        "english": "What is your name?",
        "translitation": "06480679 06270632 06cc06480631 064606cc0645061f",
        "urdu": "0622067e06a90627 064606270645 06a906cc0627 06be06d2061f",
        "audio": "0863.ogg",
        "file_type": "audio/ogg",
        "file_size": "67.251",
        "file_name": "1462028674.ogg",
        "temp_name": "/tmp/phpgnGUTo",
        "listing_a_id": "5",
        "status": "1"
    }, {
        "id": "16",
        "english": "Apple",
        "translitation": "062706cc067e0644",
        "urdu": "063306cc0628",
        "audio": "sm1_cln.wav",
        "file_type": "audio/wav",
        "file_size": "108.645",
        "file_name": "1458219047.wav",
        "temp_name": "/tmp/phpzLbtur",
        "listing_a_id": "6",
        "status": "1"
    }]
}

这是我的代码:

do {

    let json = try NSJSONSerialization.JSONObjectWithData(data2!, options: NSJSONReadingOptions()) as! [String: String]

    if let blogs = json["b_categories"] as? [[String: AnyObject]] {

        print("here 1")
        let blog = blogs[0]

        if let name = blog["english"] as? String {

            print("here 2")
            let newRecord = NSEntityDescription.insertNewObjectForEntityForName("B_categories", inManagedObjectContext: self.managedObjectContext) as! B_categories
            newRecord.english = name
            newRecord.file_name = blog["file_name"] as? String
            newRecord.listing_a_id = Int((blog["listing_a_id"] as? String)!)
        }
    }

} catch {
    print("error serializing JSON: \(error)")
}

请帮助

1 个答案:

答案 0 :(得分:1)

这不是你的JSON,或者更具体地说,那不是你在MainCtrl中所拥有的。我不知道你在data2中有什么,但我尝试通过data2运行该JSON并且它有效。您的数据blob包含的内容不同于您的想法,您需要弄清楚它是什么。但是你没有提供任何细节,所以这是一个单独的问题。

代码中至少有一个问题,但不会导致引用错误消息的问题:

JSONObjectWithData

这会失败,并导致您的应用崩溃。您的JSON不是let json = try NSJSONSerialization.JSONObjectWithData(data2!, options: NSJSONReadingOptions()) as! [String: String] ,因此在此处使用[String:String]强制进行向下转换会导致运行时错误。