Swift4中用Alamofire或SwiftyJSON解析JSON数组并提取students_id的高效方法
在Swift 4中用Alamofire + SwiftyJSON解析JSON数组并提取students_id
我来帮你梳理下在Swift 4里用Alamofire和SwiftyJSON解析JSON数组并提取students_id的高效实现方式,步骤很清晰,咱们一步步来:
第一步:先搞定依赖配置
首先得确保你已经通过CocoaPods把两个库引入项目了,在你的Podfile里加上这两行:
platform :ios, '10.0' use_frameworks! target '你的AppTarget名称' do pod 'Alamofire' pod 'SwiftyJSON' end
然后在终端运行pod install,之后一定要用生成的.xcworkspace文件打开项目,别再用原来的.xcodeproj了。
第二步:编写请求+解析的核心代码
先假设你的接口返回的JSON结构大概是这样的(如果你的结构不一样,后面我会说明调整方式):
{
"data": [
{"students_id": 1, "name": "Alice"},
{"students_id": 2, "name": "Bob"},
{"students_id": 3, "name": "Charlie"}
]
}
下面是完整的请求和解析逻辑,我加了详细的注释,方便你理解:
import Alamofire import SwiftyJSON // 定义一个带回调的函数,用来获取并提取学生ID数组 func fetchStudentIDs(completion: @escaping ([Int]?, Error?) -> Void) { let targetURL = "替换成你的实际API地址" // 用Alamofire发起GET请求 Alamofire.request(targetURL, method: .get).responseJSON { response in switch response.result { case .success(let rawData): // 把响应数据转成SwiftyJSON的JSON对象,方便操作 let json = JSON(rawData) // 先校验"data"字段是不是数组,避免后续崩溃 guard let studentsArray = json["data"].array else { let parseError = NSError(domain: "JSON解析错误", code: -1, userInfo: [NSLocalizedDescriptionKey: "返回的data字段不是数组格式"]) completion(nil, parseError) return } // 高效提取students_id:用compactMap一键转换+过滤 // compactMap会自动跳过解析失败的元素(比如students_id不存在或者不是Int类型) let studentIDs = studentsArray.compactMap { studentJSON in studentJSON["students_id"].int } // 把结果通过回调返回 completion(studentIDs, nil) case .failure(let requestError): // 请求失败时把错误返回 completion(nil, requestError) } } }
第三步:调用函数并使用结果
写完上面的函数,你就可以在需要的地方调用它,拿到提取后的学生ID数组:
// 调用函数获取学生ID fetchStudentIDs { studentIDs, error in if let error = error { print("获取学生ID失败:\(error.localizedDescription)") return } if let ids = studentIDs { print("提取到的学生ID数组:\(ids)") // 这里可以把ids存储到你需要的变量/属性里,比如: // self.studentIDArray = ids } }
特殊情况调整:如果JSON数组是根节点
如果你的接口返回的直接是一个JSON数组(而不是嵌套在data字段里),比如:
[{"students_id":1}, {"students_id":2}, {"students_id":3}]
那只需要把解析部分的json["data"].array改成json.array就行,其他逻辑不变:
guard let studentsArray = json.array else { // 错误处理 return }
高效实现的几个关键点
- 用
compactMap替代手动循环:这个方法既完成了类型转换,又自动过滤掉无效数据,代码简洁还比手动循环性能更好。 - 提前做类型校验:用
guard let确保JSON结构符合预期,避免因为接口返回异常导致崩溃,同时能及时返回明确的错误信息。 - SwiftyJSON的类型安全访问:
studentJSON["students_id"].int会尝试把值转成Int类型,失败就返回nil,配合compactMap完美处理各种异常情况。
内容的提问来源于stack exchange,提问作者Surya
相关产品推荐
相关产品推荐

