如何使用JSON

时间:2016-06-30 19:27:42

标签: json swift dictionary

假设我正在解析JSON并需要将其转换为Swift字典。如果您在下面注意到,则类型是相当嵌套的。有一个帐户键,其值为另一个映射,具有嵌套数组等。我看过很多帖子暗示AnyObject?还是什么?这样做的正确方法是什么?一个完整的例子会很棒。我正在使用Alamofire / SwiftyJSON。谢谢!

    {
        "id": "20o2k2jlkja08a08",
        "username": "catlover",
        "accounts": {
            "verified_email": "false",
            "identities": [{
                "network": "facebook",
                "token": "alkdjlaksjsak",
                "avatar": "avatarUrl"
            }, {
                "network": "twitter",
                "token": "alkdjlaksjsak",
                "avatar": "avatarUrl"
            }]
        },
        "followers": "100",
        "following": "20"
    }

2 个答案:

答案 0 :(得分:1)

我建议您查看Cocoapods上提供的ObjectMapperAlamofireObjectMapper框架。有了它们,从JSON到Swift的对象的映射非常简单。

首先,定义JSON如何映射到您的对象:

import ObjectMapper

class User: Mappable {
    var id: String?
    var username: String?
    var accounts: UserAccount?
    var followers: Int?
    var following: Int?

    required init?(_ map: Map) { /* validate your JSON, etc */ }

    func mapping(map: Map) {
        self.id         <- map["id"]
        self.username   <- map["username"]
        self.accounts   <- map["accounts"]
        self.followers  <- map["followers"]
        self.following  <- map["following"]
    }
}

class UserAccount: Mappable {
    var verifiedEmail: Bool?
    var identities: [UserIdentity]?

    required init?(_ map: Map) { }

    func mapping(map: Map) {
        self.verifiedEmail  <- map["verified_email"]
        self.identities     <- map["identities"]
    }
}

class UserIdentity: Mappable {
    var network: String?
    var token: String?
    var avatar: NSURL?

    required init?(_ map: Map) { }

    func mapping(map: Map) {
        self.network    <- map["network"]
        self.token      <- map["token"]
        self.avatar     <- (map["avatar"], URLTransform())
    }
}

用法:

Alamofire.request(.GET, url)
    .responseObject { (response: Response<User, NSError>) in
        let user = response.result.value

        // Get the url to the user's avatar
        let avatarURL = user?.accounts?.identities?.first?.avatar
    }

如果您想避开所有?,只需为您的属性提供默认值即可。当然,只有在JSON中保证属性存在时才有意义:

class User: Mappable {
    var id = ""
    var username = ""
    var accounts = UserAccount()
    var followers = 0
    var following = 0

    ...
}

答案 1 :(得分:0)

您必须将JSON文档数组/字典添加到您自己的类结构中。像这样......

public class Identity
{
    public var network: String
    public var token: String
    public var avatarURI: NSURL
}

public class Account
{
    public var verifiedEmail: Bool
    public var identities: [Identity]
}

public class Profile
{
    public var profileID: String
    public var userName: String
    public var accounts: [Account]
    public var followers: Int
    public var following: Int
}