我怎样才能解决这个问题?从“ [String]”强制转换为无关类型“ [String:AnyObject]”始终失败

时间:2018-08-29 08:22:09

标签: json swift foundation

我似乎找不到解决方案,有数百个答案,但找不到与这个简单问题相关的答案。 我试图将字典放入字符串中怎么做会失败? 原始文本

let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let jsonString = (jsonResult as AnyObject).components(separatedBy: "")                           
let jsonDict = jsonString as! [String: AnyObject]
//let jsonDict = jsonString as! [String: AnyObject]
//let jsonDict = jsonString as! Dictionary<String,String>
//Cast from '[String]' to unrelated type 'Dictionary<String, String>' always fails 

完整代码,现在可以在@Vadian修复后使用。

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    searchForMovie(title: "pulp_fiction")
}

func searchForMovie(title: String){
    //http://www.omdbapi.com/?t=pulp+fiction
    if let movie = title.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed){
        let url = URL(string: "https://www.omdbapi.com/?t=\(movie)&i=xxxxxxxx&apikey=xxxxxxxx")
        // this url contains the omnbapi keys which are free/

        let session = URLSession.shared
        let task = session.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil {
                print(error!)
            } else {
                if data != nil {
                    do {
                       let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                       if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
                            let jsonArray = jsonResult.components(separatedBy: "")
                            print(jsonArray)
                        } else {
                            print("This JSON is (most likely) not a string")
                        }

                       let jsonDict = jsonResult as! [String: Any]

                        DispatchQueue.main.async {
                        print(jsonDict)
                        }
                    } catch {
                    }
                }
            }
        })
        task.resume()
    }
}
}

其结果是:

This JSON is (most likely) not a string
["Poster": https://m.media-

amazon.com/images/M/MV5BNGNhMDIzZTUtNTBlZi00MTRlLWFjM2ItYzViMjE3YzI5MjljXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg, "BoxOffice": N/A, "Language": English, Spanish, French, "Year": 1994, "Metascore": 94, "Director": Quentin Tarantino, "Rated": R, "Runtime": 154 min, "Genre": Crime, Drama, "imdbVotes": 1,548,861, "Ratings": <__NSArrayI 0x604000256a10>(
{
    Source = "Internet Movie Database";
    Value = "8.9/10";
},
{
    Source = "Rotten Tomatoes";
    Value = "94%";
},
{
    Source = Metacritic;
    Value = "94/100";
}
)
, "Released": 14 Oct 1994, "imdbRating": 8.9, "Awards": Won 1 Oscar. Another 62 wins & 69 nominations., "Actors": Tim Roth, Amanda Plummer, Laura Lovelace, John Travolta, "Response": True, "Country": USA, "Plot": The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption., "DVD": 19 May 1998, "Title": Pulp Fiction, "Writer": Quentin Tarantino (stories), Roger Avary (stories), Quentin Tarantino, "Production": Miramax Films, "imdbID": tt0110912, "Website": N/A, "Type": movie]

1 个答案:

答案 0 :(得分:2)

首先从不对Swift 3+中的JSON值使用AnyObject。它们都是Any

发生错误是因为components(separatedBy的结果是一个数组([String]),但是您将其转换为字典([String:Any(Object)])。完全不要转换,编译器知道类型。

并且永远不要在Swift中使用.mutableContainers。此选项没有意义。

components(separatedBy仅在JSON是字符串时才有意义。如果是这样,您必须通过选项.allowFragments

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
   let jsonArray = jsonResult.components(separatedBy: "") 
   print(jsonArray)
} else {
    print("This JSON is (most likely) not a string")
} 

编辑:

根据您添加的结果,接收到的对象显然是字典,因此as? String以及components(separatedBy:.allowFragments是错误的。试试这个

if let jsonDictionary = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
   for (key, value) in jsonDictionary {
       print(key, value)
   }
} else {
    print("This JSON is not a dictionary")
}