我需要在下面的json中获取所有“students_id”值并将其存储在数组中。请告诉我有效的方法来执行此操作。请帮助。谢谢
{
"status": "success",
"user": [
{
"student_id": 1,
"first_name": "Student 1",
"last_name": "Student 1",
"emergency_contact_person": null,
"dob": "0000-00-00",
"class_section_id": 1,
"class_section_name": "A",
"class_id": 1,
"class_name": "10th"
},
{
"student_id": 2,
"first_name": "Student 2",
"last_name": "Student 2",
"emergency_contact_person": null,
"dob": "0000-00-00",
"class_section_id": 1,
"class_section_name": "A",
"class_id": 1,
"class_name": "10th"
}
],
"response": 200
}
你可以使用Codable
协议。如果您的JSON返回,只需创建一个镜像结构的结构:
struct Response: Codable {
let status: String
let user: [Student]
}
struct Student: Codable {
let student_id: Int
let first_name: String
let last_name: String
let emergency_contact_person: String?
let dob: String
let class_section_id: Int
let class_section_name: String
let class_id: Int
let class_name: String
}
从那里,您将使用JSONDecoder
解码您的JSON,然后使用map
从中提取您需要的ID:
let jsonData = json.data(using: .utf8)
let decoder = JSONDecoder()
var studentIDs: [Int] = []
if let jsonData = jsonData {
do {
let responseStruct = try decoder.decode(Response.self, from: jsonData)
studentIDs = responseStruct.user.map{$0.student_id}
} catch {
print("\(error): \(error.localizedDescription)")
}
}
这是post re: decoding JSONs in Swift 4的链接。
如果你不需要JSON中的所有东西,那么你可以简单地缩写你的结构来解析你需要的元素。在此示例中,您可以将结构缩写为如下所示:
struct Response: Codable {
let user: [Student]
}
struct Student: Codable {
let student_id: Int
}
您总是可以使用for
循环并遍历user
下的每个部分
for string["users"].each do |x| # => string has your PARSED json
return x["student_id"]
end
代码是用ruby
编写的,但您将对如何操作有一个基本的了解。