如何修复错误可以在swift中将[NSDictionary]转换为NSDictionary?

时间:2016-06-21 15:22:24

标签: ios swift uitableview swift2

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

导入基金会 class 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)"
}

}

导入基金会 class 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)"

}

}

导入基金会 class 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"
      }
    ]
  }
}

3 个答案:

答案 0 :(得分:0)

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

例如。

let myProfile = profile.firstObject

答案 1 :(得分:0)

NSDictionary而非[NSDictionary]

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

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

for profile in profile {
    print(profile)
}

答案 2 :(得分:0)

有效的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
}