【问题标题】:How to use SwiftyJSON to read values from JSON with multiple objects and arrays如何使用 SwiftyJSON 从具有多个对象和数组的 JSON 中读取值
【发布时间】:2016-08-16 08:24:29
【问题描述】:

我有这个 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["user"][0]["id"].string
  • @EICaptainv2.0 谢谢你的工作!!!!
  • 即使提供链接也请提供相关代码。您提供的 json 中没有“律师”字段;也链接不适合我。

标签: json swift swifty-json


【解决方案1】:

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

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

之后,您将能够使用“用户”数组中的项目并访问其值。

这是我使用的一个函数。它的输入是我正在使用的 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

注意:要将其存储在字典中,您必须使用 String(id) 将其转换为字符串。这种存储数据的方法不是最好的,我用这个是因为我通常有字符串,只有一个整数。

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

PS:JSON 数据中有一个错字:phone_namber。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2019-04-22
    相关资源
    最近更新 更多