如何修复错误无法将 [NSDictionary] 快速转换为 NSDictionary?

Posted

技术标签:

【中文标题】如何修复错误无法将 [NSDictionary] 快速转换为 NSDictionary?【英文标题】:How to fix error can covert [NSDictionary] to NSDictionary in swift? 【发布时间】:2016-06-21 15:22:24 【问题描述】:

我正在尝试在 tableviewcells 上显示我的 json 数据。但是,我在将 json 结果附加到我的个人资料 homemodel 时遇到问题。我的请求管理器出现错误,提示无法将 [NSDictionary] 转换为 NSDictionary

导入基础 类 coreValueHomeModel

//MARK: - properties
var total: String = "total"
var commentId: String = "commentId"

//construct
init(jsonData: NSDictionary)
    total = jsonData.objectForKey("total") as? String ?? "total"
    commentId = jsonData.objectForKey("commentId") as? String ?? "commentId"


//construct
init(total: String, commentId: String) 
    self.total = total
    self.commentId = commentId


//prints object's UserInformation
var description: String 
    return "total:\(total), commentId:\(commentId)"

导入基础 类StrengthHomeModel

//MARK: - properties
var id: String = "id"
var name: String = "name"
var description: String = "description"
var color: String = "color"

//construct
init(jsonData: NSDictionary)
    id = jsonData.objectForKey("id") as? String ?? "id"
    name = jsonData.objectForKey("name") as? String ?? "name"
    description = jsonData.objectForKey("description") as? String ?? "description"
    color = jsonData.objectForKey("color") as? String ?? "color"


//construct
init(id: String, name: String, description: String ,color: String) 
    self.id = id
    self.name = name
    self.description = description
    self.color = color


//prints object's UserInformation
var des: String 
    return "id: \(id), name: \(name), description: \(description), color: \(color)"


导入基础 类 ProfileHomeModel

//MARK: - properties
var firstName: String? = "First Name"
var lastName: String? = "Last Name"
var location: String? = "location"
var title: String? = "title"
var score: String? = "score"
var received: String? = "received"
var given: String? = "given"
var coreValueResults = [coreValueHomeModel]()
var strengthResults = [StrengthHomeModel]()

init(jsonData: NSDictionary)
    firstName = jsonData.objectForKey("firstName") as? String ?? "First Name"
    lastName = jsonData.objectForKey("lastName") as? String ?? "Last Name"
    location = jsonData.objectForKey("location") as? String ?? "location"
    title = jsonData.objectForKey("title") as? String ?? "title"
    score = jsonData.objectForKey("score") as? String ?? "score"
    received = jsonData.objectForKey("received") as? String ?? "received"
    given = jsonData.objectForKey("given") as? String ?? "given"

    if let commentTotals = jsonData.objectForKey("commentTotals") as? [NSDictionary] 
        for commentTotal in commentTotals 
            let coreValue = coreValueHomeModel(jsonData: commentTotal)
            coreValueResults.append(coreValue)
        

    

    if let strengths = jsonData.objectForKey("strengths") as? [NSDictionary] 
        for strength in strengths 
            let strengthValue = StrengthHomeModel(jsonData: strength)
            strengthResults.append(strengthValue)
        

    



init()
    firstName = nil
    lastName = nil
    location = nil
    title = nil
    score = nil
    received = nil
    given = nil
    coreValueResults = []
    strengthResults = []

import Foundation

class ProfileRequestManager 

    func parseJson() -> ProfileHomeModel  
        var profileValue = ProfileHomeModel()

        let urlPath = "*********"
        let url = NSURL(string: urlPath)
        let data = NSData(contentsOfURL: url!)

        do 
          let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary

                print(jsonData)
                let profile = jsonData!.objectForKey("profile") as? NSDictionary

            for profileInfo in profile! 
                print(profileInfo)
//problem here
                profileValue.append(ProfileHomeModel(jsonData: profileInfo))

            

        
    catch
     print("Something went wrong while parsing json data fetched from the API")
    
        return profileValue

        
    

以及NSData(contentsOfURL:)检索到的数据样本:


  "success": true,
  "profile": 
    "firstName": "Vignesh",
    "lastName": "Krish",
    "score": "126",
    "title": "Software Developer Intern",
    "given": "4",
    "received": "10",
    "commentTotals": [
      
        "total": "4",
        "id": "8"
      ,
      
        "total": "3",
        "id": "9"
      ,
      
        "total": "2",
        "id": "10"
      ,
      
        "total": "1",
        "id": "11"
      
    ],
    "strengths": [
      
        "id": "4",
        "name": "Analytical",
        "description": "People exceptionally talented in the Analytical theme search for reasons and causes. They have the ability to think about all the factors that might affect a situation.",
        "color": "9c0000"
      ,
      
        "id": "17",
        "name": "Focus",
        "description": "People exceptionally talented in the Focus theme can take a direction, follow through, and make the corrections necessary to stay on track. They prioritize, then act.",
        "color": "5c3a6e"
      ,
      
        "id": "8",
        "name": "Communication",
        "description": "People exceptionally talented in the Communication theme generally find it easy to put their thoughts into words. They are good conversationalists and presenters.",
        "color": "da892f"
      ,
      
        "id": "29",
        "name": "Responsibility",
        "description": "People exceptionally talented in the Responsibility theme take psychological ownership of what they say they will do. They are committed to stable values such as honesty and loyalty.",
        "color": "5c3a6e"
      ,
      
        "id": "30",
        "name": "Restorative",
        "description": "People exceptionally talented in the Restorative theme are adept at dealing with problems. They are good at figuring out what is wrong and resolving it.",
        "color": "5c3a6e"
      
    ]
  

【问题讨论】:

在我看来,对象被序列化为直接字典,而不是字典数组。你能发布你通过NSData(contentsOfURL:)检索到的数据的相关sn-p吗? 我发布了我试图以 json 格式检索的数据 好吧,你的数据 sn-p 很清楚地显示了你的问题:profile 是一个字典。您正在尝试将其转换为一系列字典。将您的演员表从 [NSDictionary] 更改为 NSDictionary 我按照您的说法进行了更改。它给了我一个错误,说 profilehomemodel 没有附加成员类型 【参考方案1】:

您正在尝试将数组 ([NSDictionary]) 转换为单个 NSDictionary,这是不允许的。访问您必须获取的数组以获取您正在寻找的数组。

例如。

let myProfile = profile.firstObject

【讨论】:

【参考方案2】:

这是NSDictionary 不是[NSDictionary]

let profile = jsonData!.objectForKey("profile") as? NSDictionary

您的代码还有其他问题,如下所示,这些问题没有意义并且会导致错误。

for profile in profile 
    print(profile)

【讨论】:

我按照您的说法进行了更改。它给了我一个错误,说 profilehomemodel 没有附加成员类型 @VigneshKrish 您的代码有几个问题,我无法为您解决所有问题。提示:JSON 节点永远不会是 [NSDictionary],您可能不想使用 for 循环访问 NSDictionary【参考方案3】:

有效的 json 字符串可以是数组或字典。如果你不知道 json 字符串的格式是什么,你应该在操作它的内容之前检查它的类型。

do 
    if let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary 
        //got a dictionary, do your works with this dictionary
     else if let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSArray 
        //got an array, do your works with this dictionary
     else 
        //is not a valid json data
    
 catch let _error as NSError 
   //got error

【讨论】:

以上是关于如何修复错误无法将 [NSDictionary] 快速转换为 NSDictionary?的主要内容,如果未能解决你的问题,请参考以下文章

如何修复 ASP.NET 中的“此页面无法显示”错误?

“-[__NSDictionaryI 长度]:无法识别的选择器发送到实例”没有 NSDictionary 的错误?

如何修复 Magento-1.9.4 中的“无法将 VCL 应用到 127.0.0.1:6082:无法从 Varnish 读取响应代码”错误

Swift - 无法将“__NSCFString”类型的值转换为“NSDictionary”

发送到实例的 iOS 无法识别的选择器 - 将 NSDictionary 添加到 NSMutableArray

在 NSDictionary 中传递 NSDate 并转换为 NSData 以进行 jsondata 修复