将本地 JSON 文件解析成 Coredata 会导致错误

Posted

技术标签:

【中文标题】将本地 JSON 文件解析成 Coredata 会导致错误【英文标题】:Parsing a local JSON file into Coredata leads to an error 【发布时间】:2020-11-23 12:49:17 【问题描述】:

我正在尝试解析包含 3 个字典的本地 JSON 文件,每个字典在 Coredata 中都有自己的数组,但我不断收到以下错误:

Could not cast value of type '__NSDictionaryM' (0x7fff86b93f10) to 'NSArray' (0x7fff86b92430).

我正在使用以下代码:

private func preloadData() 
    
    // Get a reference to User Defaults
    let defaults = UserDefaults.standard
    
    // Get a reference to the persitent container
    let context = persistentContainer.viewContext
    
    // Check if this is the first launch
    if defaults.bool(forKey: Constants.PRELOAD_DATA) == false 
        
        // Parse the Json
        let path = Bundle.main.path(forResource: "JSONProjectFinal", ofType: "json")
        
        // Check that path isn't nil
        guard path != nil else  return 
        
        // Create a URL
        let url = URL(fileURLWithPath: path!)
        
        do 
            // Get the data
            let data = try Data(contentsOf: url)
            
            // Attempt to parse the Json Array
            let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String:Any]]
            print(jsonArray)

            // Loop through the Json array
            for d in jsonArray 
                
                // Create the book objects and populate them
                
                // Populate the Fantasy books
                let f = Fantasy(context: context)
                f.name = d["name"] as? String
                f.imagename = d["imagename"] as? String
                f.date = d["date"] as? String
                f.summary = d["summary"] as? String
                
                // Populate the Adventure books
                let a = Adventure(context: context)
                a.name = d["name"] as? String
                a.imagename = d["imagename"] as? String
                a.date = d["date"] as? String
                a.summary = d["summary"] as? String
                
                // Populate the SciFi books
                let sci = SciFi(context: context)
                sci.name = d["name"] as? String
                sci.imagename = d["imagename"] as? String
                sci.date = d["date"] as? String
                sci.summary = d["summary"] as? String
            

         catch  return 

这是 JSON 文件的 sn-p


    "fantasy": [
        
            "name": "Fellowship of the Ring",
            "imagename": "lotr",
            "date": "24 July 1964",
            "summary": "The Fellowship of the Ring is the first of three volumes in The Lord of the Rings, an epic set in the fictional world of Middle-earth. The Lord of the Rings is an entity named Sauron, the Dark Lord, who long ago lost the One Ring that contains much of his power. His overriding desire is to reclaim the Ring and use it to enslave all of Middle-earth"
        ,
        
            "name": "Harry Potter and the Deathly Hallows",
            "imagename": "harrypotter",
            "date": "21 July 2007",
            "summary": "Without the guidance and protection of their teachers, Harry, Ron and Hermione set out on a mission to destroy the horcruxes, which are the sources of Voldemort's immortality. Although they must trust each other more than ever, forces of darkness threaten to separate them. Voldemort's Death Eaters have taken control of the Ministry of Magic and Hogwarts, and they are looking for Harry as he and his friends prepare for the final confrontation."
        
    ]

那么,我该怎么做呢?我应该将其转换为数组字典吗? 总的来说,我对编程很陌生,因此我们将不胜感激!

【问题讨论】:

不是答案,但我建议您切换到Codable 协议而不是JSONSerialization。您可以粘贴您的 JSON here,它会为您生成数据模型。 【参考方案1】:

你的根是字典而不是数组

guard let res = try JSONSerialization.jsonObject(with: data, options:[:]) as? [String:Any] ,  
      let jsonArray = res["fantasy"] as? [[String:Any]] else  return 

【讨论】:

这适用于我的第一个字典,但我如何添加剩余的两个?

以上是关于将本地 JSON 文件解析成 Coredata 会导致错误的主要内容,如果未能解决你的问题,请参考以下文章

java怎么将json文件读取进来并转成map

GoLang -- json文件操作

android json解析成map格式

如何将资产文件夹中的本地 JSON 文件解析为 ListView?

Flutter 从本地化 JSON 文件解析数组

java解析本地json文件