如何在嵌套的 JSON 值上使用 SwiftyJSON [英] How to use SwiftyJSON on nested JSON values
问题描述
我正在调用一个 JSON API,它有几个我需要获取的嵌套值.我正在使用 SwiftyJSON 使事情变得更简洁.对于顶级值,一切似乎都运行良好,但在更深层次上,我得到了可怕的展开可选值时为零".
I'm calling a JSON API that has several nested values that I need to get. I'm using SwiftyJSON to make things a little cleaner. For the top level values, everything seems to be working fine, but on anything deeper, I'm getting the dreaded "nil when unwrapping optional value."
这是我如何使用 Alamofire 进行 API 调用:
Here is how I'm making the API call with Alamofire:
Alamofire.request(APIRequests.Router.Nearby(self.page)).responseJSON(){
(_,_,json,_) in
println(json)
if (json != nil){
var jsonObj = JSON(json!)
if let userArray = jsonObj ["results"].array {
for userDict in userArray {
var username: String! = userDict["username"].string
var firstName: String! = userDict["firstName"].string
var profileImage: String! = userDict["userImages"]["profile"]["filename"].string
var characterName: String! = userDict["characters"]["characterName"].string
var user = User(username: username, profileImage: profileImage, firstName: firstName, characterName: characterName)
self.users.append(user)
}
}
这是一个 JSON 示例:
Here is a sample of the JSON:
{
userInfo: {
something: "abc",
requestType: "GET"
},
results: [
{
username: "Jess",
firstName: "Jessica",
userImages: {
profile: [
{
userImageID: "6",
filename: "user-07.jpg"
}
],
cover: [
{
userImageID: "15",
filename: "user-07.jpg"
}
]
},
characters: [
{
userCharacterID: "8",
characterName: "Amelia",
}
]
}
对于顶级键 username
和 firstName
,调试器显示了正确的值,但是,只要我深入一点以获得 profileImage
或 characterName
即使打印 json 显示这些键的值,它们也会返回 nil.
For the top level keys username
and firstName
the debugger is showing the correct values, however, as soon as I dive a little deeper to get profileImage
or characterName
these are coming back as nil even though printing the json shows values for those keys.
我做错了什么?我只是没看到.
What am I doing wrong? I'm just not seeing it.
任何想法都会有所帮助.谢谢.
Any thoughts would be helpful. Thank you.
推荐答案
尝试
var profileImage: String! = userDict["userImages"]["profile"][0]["filename"].string
var characterName: String! = userDict["characters"][0]["characterName"].string
并让我们知道它提供了什么.
and let us know what it gives.
这篇关于如何在嵌套的 JSON 值上使用 SwiftyJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!