如何从二维码读取的JSON字符串中提取指定键对应的值?
提取二维码JSON字符串中的指定字段值
你可以通过两种方式解析读取到的JSON字符串,提取sectionName、sectionExt、sectionLocation三个字段的值:
方法1:使用Codable模型解析(推荐)
这种方式类型安全,能避免键名拼写错误和类型不匹配的问题,步骤如下:
1. 定义对应的数据模型
创建一个遵循Codable协议的结构体,和JSON的字段一一对应:
struct SectionInfo: Codable { let sectionName: String let sectionExt: String let sectionLocation: String }
2. 修改二维码读取代码
在metadataOutput方法中,将读取到的字符串转成Data,再用JSONDecoder解析为模型实例,之后直接访问属性即可:
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject, let jsonString = metadataObject.stringValue, let jsonData = jsonString.data(using: .utf8) else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) do { let sectionInfo = try JSONDecoder().decode(SectionInfo.self, from: jsonData) print("sectionName: \(sectionInfo.sectionName)") print("sectionExt: \(sectionInfo.sectionExt)") print("sectionLocation: \(sectionInfo.sectionLocation)") } catch { print("解析失败:\(error.localizedDescription)") } session.stopRunning() self.dismiss(animated: true, completion: nil) }
方法2:解析为字典(灵活但无类型校验)
如果不需要严格的类型校验,也可以直接将JSON解析成字典,通过键名取值:
修改二维码读取代码
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject, let jsonString = metadataObject.stringValue, let jsonData = jsonString.data(using: .utf8) else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) do { if let sectionDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: String] { let sectionName = sectionDict["sectionName"] ?? "" let sectionExt = sectionDict["sectionExt"] ?? "" let sectionLocation = sectionDict["sectionLocation"] ?? "" print("sectionName: \(sectionName)") print("sectionExt: \(sectionExt)") print("sectionLocation: \(sectionLocation)") } } catch { print("解析失败:\(error.localizedDescription)") } session.stopRunning() self.dismiss(animated: true, completion: nil) }
注意事项
- 两种方法都需要处理解析失败的情况(比如JSON格式错误、字段缺失等)
- 推荐使用
Codable模型的方式,长期维护更可靠
内容的提问来源于stack exchange,提问作者Alshaman
相关产品推荐
相关产品推荐

