【问题标题】:How to parse this json example with SwiftyJSON?如何使用 SwiftyJSON 解析这个 json 示例?
【发布时间】:2016-07-15 00:27:22
【问题描述】:
{"title" : "saved users", "saved_users_list" :

[
{"username" : "Danny7", "name" : "Danny", "email" : "danny@email.com"},

{"username" : "Ike2016", "name" : "Ike", "email" : "ike@email.com"},

{"username" : "john202", "name" : "John", "email" : "john@email.com"},

{"username" : "ray_mundo", "name" : "Raymundo", "email" : "ray@email.com"}

]
}

我正在尝试用 SwiftyJSON 解析这个 json,但它不起作用。

json["saved_users_list"].count == 0

json["saved_users_list"][0]["username"] does not equal "Danny7"

json["title"] == null

我是这样获取数据的:

Alamofire.request(.POST, url, parameters: parameters).validate().responseString { response in
            switch response.result {
            case .Success:
                if let value = response.result.value {
                    value = JSON(value)
                    print(value)
                }
        }

print(value) 打印上面列出的 json。

【问题讨论】:

  • 到目前为止你能分享你的代码吗? (例如,你如何解析 JSON?你怎么知道它看起来像你在这里分享的?)
  • 哦,是的,可能是我没有正确地将字符串转换为 json

标签: ios json swift swifty-json


【解决方案1】:

你可以试试把JSON(value)这样放

Alamofire.request(.POST, url, parameters: parameters).responseJSON { (response) in
        switch response.result {
        case .Success(let value) :
            let swiftyJSON = JSON(value)
            print(swiftyJSON)
        }
    }

希望对你有帮助

【讨论】:

  • 你说得对。出于某种原因,当它需要成为 .POST 时,我不小心做了一个 .GET。在执行 .GET 时,我实际上得到了一个空的 json 对象。谢谢!!!
【解决方案2】:

Alamofire 通常不会尝试为您解析 JSON 吗?如果您使用responseJSON 并且不要自己调用JSON(...),请查看您的代码是否工作得更好。即:

Alamofire.request(.POST, url, parameters: parameters).validate().responseJSON { response in
    switch response.result {
    case .Success:
        if let value = response.result.value {
            print(value)
        }
    }
}

【讨论】:

  • value 将是一个字符串,我无法使用 SwfityJSON 解析字符串
  • @walton 哦,对不起,如果你想让 Alamofire 为你解析 JSON,需要使用 responseJSON。请参阅我的编辑,尽管您的代码应该做几乎相同的事情。如果不查看您正在解析的确切字符串或通过知道 URL 和参数能够重现,这将很难调试。
【解决方案3】:

a希望这个类可以解决你的问题,它是使用 SwiftyJSONAccelerator 模型生成器生成的。

public class BaseClass: NSObject, NSCoding {

// MARK: Declaration for string constants to be used to decode and also serialize.
internal let kBaseClassTitleKey: String = "title"
internal let kBaseClassSavedUsersListKey: String = "saved_users_list"


// MARK: Properties
public var title: String?
public var savedUsersList: [SavedUsersList]?


// MARK: SwiftyJSON Initalizers
/**
Initates the class based on the object
- parameter object: The object of either Dictionary or Array kind that was passed.
- returns: An initalized instance of the class.
*/
convenience public init(object: AnyObject) {
    self.init(json: JSON(object))
}

/**
Initates the class based on the JSON that was passed.
- parameter json: JSON object from SwiftyJSON.
- returns: An initalized instance of the class.
*/
public init(json: JSON) {
    title = json[kBaseClassTitleKey].string
    savedUsersList = []
    if let items = json[kBaseClassSavedUsersListKey].array {
        for item in items {
            savedUsersList?.append(SavedUsersList(json: item))
        }
    } else {
        savedUsersList = nil
    }

}


/**
Generates description of the object in the form of a NSDictionary.
- returns: A Key value pair containing all valid values in the object.
*/
public func dictionaryRepresentation() -> [String : AnyObject ] {

    var dictionary: [String : AnyObject ] = [ : ]
    if title != nil {
        dictionary.updateValue(title!, forKey: kBaseClassTitleKey)
    }
    if savedUsersList?.count > 0 {
        var temp: [AnyObject] = []
        for item in savedUsersList! {
            temp.append(item.dictionaryRepresentation())
        }
        dictionary.updateValue(temp, forKey: kBaseClassSavedUsersListKey)
    }

    return dictionary
}

// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
    self.title = aDecoder.decodeObjectForKey(kBaseClassTitleKey) as? String
    self.savedUsersList = aDecoder.decodeObjectForKey(kBaseClassSavedUsersListKey) as? [SavedUsersList]

}

public func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(title, forKey: kBaseClassTitleKey)
    aCoder.encodeObject(savedUsersList, forKey: kBaseClassSavedUsersListKey)

}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多