如何使用SwiftyJSON从具有多个对象和数组的JSON中读取值

如何使用SwiftyJSON从具有多个对象和数组的JSON中读取值,json,swift,swifty-json,Json,Swift,Swifty Json,我有这个JSON,我想使用SwiftyJSON库访问这些值: {"user":[{"id":"33","id_number":"0","first_name":"tom","last_name":"lily","city":"jeddah","gender":"0","DOB":"0000-00-00","phone_namber":"0000000000","email":"000"}, {"id":"34","id_number":"0","first_name":"tom","last_n

我有这个JSON,我想使用SwiftyJSON库访问这些值:

{"user":[{"id":"33","id_number":"0","first_name":"tom","last_name":"lily","city":"jeddah","gender":"0","DOB":"0000-00-00","phone_namber":"0000000000","email":"000"},
{"id":"34","id_number":"0","first_name":"tom","last_name":"lily","city":"jeddah","gender":"0","DOB":"0000-00-00","phone_namber":"0000000000","email":"000"}]}
此JSON包含数组和对象。当我尝试这个时,它不起作用:

JSON["lawyers"]["id"].intValue
如何访问此JSON中的
id
和其他值?

首先,此JSON中没有“律师”,它永远不会开始解析数据。其次,所有的值都是字符串类型,所以如果您想将它们用作Int,就必须转换它们

因此,您有一个“用户”数组,这意味着您必须遍历该数组

之后,您将能够处理“user”数组中的项并访问其值

这是我使用的一个函数。它的输入是我正在使用的JSON,并将其存储在字典中

var dataArray = [[String: String]]() // Init dictionary

func parseJSON(json: JSON) {
    for item in json["user"].arrayValue { // This is the JSON array which contains the values that you need
        let id = item["id"].stringValue // You access the value here
        let first_name = item["first_name"].stringValue
        let last_name = item["last_name"].stringValue
        let email = item["email"].stringValue

        let obj = ["id": id, "first_name": first_name, "last_name": last_name, "email": email]
        dataArray.append(obj) // This appends the JSON parsed data to an array of dictionaries
    }
}
此项的用法:

func usingTheParsedJSON(){
    for user in dataArray {
        print("user's id: ", user["id"], ", last_name: ", user["last_name"])
        let convertedId: Int = Int(user["id"]) // If you want to use the id as Int. With this dictionary, you can only store it as String, since everything has to have the same type
    }
}
如果您可以编辑JSON数据,那么通过删除引号,您可以在解析JSON时将数字用作整数

let id = item["id"].intValue // This goes into the func's for loop
注意:要将其存储在字典中,您必须将其转换为带有字符串(id)的字符串。这种存储数据的方法不是最好的,我使用这种方法是因为我通常有字符串,只有一个整数

我希望这能解决你的问题。如果你还需要什么,请告诉我


PS:JSON数据中有一个输入错误:phone_namber。

JSON[“用户”][0][“id”]。string
@EICaptainv2.0感谢您的工作!!!!请提供相关代码,即使您提供链接。您提供的json中没有“律师”字段;链接也不是为我工作。