gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:36:28 27 4
gpt4 key购买 nike

我有这个 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 中没有“律师”,它永远不会开始解析数据。其次,所有的值都是String类型,所以如果你想把它们当作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

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

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

PS:JSON 数据中有一个拼写错误:phone_namber。

关于json - 如何使用 SwiftyJSON 从具有多个对象和数组的 JSON 中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969943/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com