Swift:无法解析 JSON 数据 [重复]

Posted

技术标签:

【中文标题】Swift:无法解析 JSON 数据 [重复]【英文标题】:Swift: Unable to parse JSON data [duplicate] 【发布时间】:2017-06-22 10:51:04 【问题描述】:

当我检查时,服务运行良好: http://lyrics.wikia.com/api.php?func=getSong&artist=Tom+Waits&song=new+coat+of+paint&fmt=json

但是当我在 Swift 中尝试时,我的数据显示为“233 字节”。

有人知道怎么回事吗?

这是我的代码:

func getWikiaInfo(completionHandler: @escaping (_ success: Bool?, _ error: NSError?) -> Void) 

    let url = URL(string: "http://lyrics.wikia.com/api.php?func=getSong&artist=Tom+Waits&song=new+coat+of+paint&fmt=json")!
    let request = URLRequest(url: url)

    let task = URLSession.shared.dataTask(with: request)  (data, response, error) in

        // no error, woohoo!
        if error == nil 

            // there was data returned
            if let data = data 

                let parsedResult: [String:AnyObject]!
                do 
                    parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]
                 catch 
                    print("Could not parse the data as JSON: '\(data)'")
                    return
                

                print(parsedResult)
                    completionHandler(true, nil)
                
            
        

【问题讨论】:

您的 JSON 无效 另见***.com/q/41183709/1187415 谢谢大家。我找到了我的答案。它不是真正的 JSON。 查看 Martin 发布的重复链接。我在另一个线程上为完全相同的问题提供了完整的答案,包括生成 JSON 的不同查询。 【参考方案1】:

您的 API Json 数据似乎无法解析。即使在线解析器也无法解析您的 API 数据。请查看下图。

【讨论】:

以上是关于Swift:无法解析 JSON 数据 [重复]的主要内容,如果未能解决你的问题,请参考以下文章