Json 错误 typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue:

时间:2021-06-01 00:10:27

标签: ios swift xcode

import UIKit
import Foundation


class ViewController: UIViewController{
    
    

    @IBOutlet weak var tableView: UITableView!
    
    var movies = [MoviesModel]()
    let decoder = JSONDecoder()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        getJson {
            print("successfully")
        }
        
        
        // Do any additional setup after loading the view.
    }
    
    func getJson(completed: @escaping () -> ()){
        let url = URL(string: "https://api.androidhive.info/json/movies.json")
        
        URLSession.shared.dataTask(with: url!) {
            (data,response,error) in
            
            if error == nil {
                do{
                    self.movies = try

                        JSONDecoder().decode([MoviesModel].self,from:data!)
                    
                    DispatchQueue.main.async {
                        completed()
                        
                    }
                }catch{
                    print("Json Error  \(error)")
                }
            }
        }.resume()
    }


}

谁能帮我解决这个错误

<块引用>

Json Error typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "releaseYear", intValue: nil)], debugDescription: “预期解码字符串,但找到了一个数字。”,underlyingError: nil))

1 个答案:

答案 0 :(得分:0)

我建议花更多时间了解您发布的代码中发生的事情,并进行简要概述:

let decoder = JSONDecoder()
let decodedMovies = decoder.decode([MoviesModel].self, from:data!)

在这里,您尝试解码从请求到电影请求收到的数据。不完全确定您的模型的外观,但您似乎确实想像以下那样定义它:

struct MoviesModel: Codable {
  let title: String
  let image: String
  let rating: Double
  let releaseYear: Int
  let genre: [String]
}

这应该有助于解决您的解码问题,如您发布的错误中所述。

另请查看有关该主题的 Apple 文档 - https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

相关问题