iTunes API - Ошибка массива JSON Swift4, Треб.для отображения в Collection View как Array - PullRequest
0 голосов
/ 15 февраля 2019

Мой ответ json:

{      resultCount = 32;
            results =     (
                        {
                    artistId = 909253;
                    artistName = "Jack Johnson";
                    country = USA;
                    currency = USD;
                    kind = "music-video";
                },
                        {
                    artistId = 909253;
                    artistName = "Jack Johnson";
                    country = UK;
                    currency = USD;
                    kind = "music-video";

                }

Я написал код для загрузки представления для вызова метода get,

Alamofire.request("https://itunes.apple.com/search?term=jackjohnson&entity=musicVideo").responseJSON  { response in
            debugPrint(response)
            if let json = response.result.value  //getting json
            {
                print(json)

                let jobsArray : NSArray  = json as! AnyHashable as! NSArray //converting json to NSArray
                if jobsArray.count > 0
                {
                    for object in jobsArray
                    {
                        if let singleDict = object as? NSDictionary
                        {
                            self.arrFavAdsList.add(singleDict)
                            print(self.arrFavAdsList)
                        }
                    }
                    DispatchQueue.main.async() {
                        self.collectionView.reloadData()
                    }
                    //displaying data in tableview
                }

            }

        }

Но он показывает ошибку массива json. Мне нужнополучить ответ массива в виде словаря и показать его в моем представлении коллекции

Ответы [ 3 ]

0 голосов
/ 15 февраля 2019

Содержимое вашего JSON представляет собой словарь, и вы не можете преобразовать его таким образом.Вот рабочая версия:

Alamofire.request("https://itunes.apple.com/search?term=jackjohnson&entity=musicVideo").responseJSON { response in
    if let json = response.result.value as? [String: Any], let tracks = json["results"] as? Array<[String: Any]>, tracks.count > 0 {
        for track in tracks {
            // do your stuffs with track here.
        }
    }
}

Однако я бы предпочел, чтобы вы использовали Codable / Decodable для анализа JSON в Swift.Для справки вы можете взглянуть на следующий пример:

struct APIResult: Codable {
    struct Track: Codable {
        let kind: String
        let artistName: String
        let name: String

        enum CodingKeys : String, CodingKey {
            case kind
            case artistName
            case name = "trackName"
        }
    }

    let resultCount: Int
    let tracks: [Track]

    enum CodingKeys : String, CodingKey {
        case resultCount
        case tracks = "results"
    }
}

// and then use it like following:

Alamofire.request("https://itunes.apple.com/search?term=jackjohnson&entity=musicVideo").response { response in
    let decoder = JSONDecoder()
    let tracks = try! decoder.decode(APIResult.self, from: response.data!).tracks
    for track in tracks {
        // do your stuffs with track here.
    }
}

Счастливого кодирования!

0 голосов
/ 19 февраля 2019

Прежде всего объявляйте переменные в вашем контроллере представления или в другом месте.

var mArray:[Music] = []

Попробуйте использовать Codable / Decodable Json parse для получения ApiResults,

struct ApiResults:Decodable {
    let resultCount: Int
    let results: [Music]
}

struct Music:Decodable {
    let artistId: Int?
    let artistName: String?
    let country: String?
    let currency: String?
    let kind: String?
}

Теперь попробуйте вваш viewdidload или вызовите его как функцию, где бы вы ни хотели ...

func callAPI() {

 guard let url = URL(string: "https://itunes.apple.com/search?term=jackjohnson&entity=musicVideo") else {return}

  URLSession.shared.dataTask(with: url){(data, response, error) in
  guard let data = data else {return}
           do
                {
       let apiressults = try JSONDecoder().decode(ApiResults.self, from: data)
                                for item in apiressults.results
             {if let track_Name = item.trackName, let artist_Name = item.artistName, let country = item.country, let currency = item.currency, let kind = item.kind
     {let musics = Music(artistId: artist_Id, artistName: artist_Name, country: country, currency: currency, kind: kind)
                     self.mArray = apiressults.results
                                       }
                                }
             DispatchQueue.main.async
                     {
                      self.collectionView.reloadData()
                     } }
                            catch let jsonError
                            {
                                print("Error:", jsonError)
                            }
                            }.resume()
    }

Теперь, наконец, как вы упомянули, чтобы показать его в виде коллекции как массив / список.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
               return mArray.count
            }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell // your cell identifier..
      cell.label1.text = mArray[indexPath.row].trackName
      cell.label2.text = mArray[indexPath.row].trackId
      cell.label3.text = mArray[indexPath.row].currency. 
///////like so for other stuffs which u need to show in collection view.
                    }
       return cell 
                }
0 голосов
/ 15 февраля 2019

Ваше полное содержимое JSON - это словарь, поэтому вам нужно преобразовать первую строку JSON в словарь. Используйте следующий код, чтобы преобразовать JSON в словарь, а затем извлечь массив результатов из словаря и загрузить в свой UICollectionview

func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...