Как я могу это исправить? Преобразование из «[String]» в несвязанный тип «[String: AnyObject]» всегда завершается неудачно - PullRequest
0 голосов
/ 29 августа 2018

Кажется, я не могу найти решение этой проблемы, есть сотни ответов, но ни один из них не связан с этой простой проблемой. Что я делаю, чтобы попытаться поместить словарь в строку, не получается? Исходный текст :

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 голосов
/ 29 августа 2018

Прежде всего никогда используйте AnyObject для значений JSON в Swift 3+. Все они Any.

Ошибка возникает потому, что результатом components(separatedBy является массив ([String]), но вы преобразуете его в словарь ([String:Any(Object)]). Не приводите вообще, тип знает компилятор.

И не используйте .mutableContainers в Swift, никогда. Эта опция бессмысленна.

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

Edit:

Согласно вашему добавленному результату полученный объект, по-видимому, является словарем, поэтому 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")
} 
...