ios - 如何在 Swift 中解析 Json 响应
问题描述
我需要解析出“选择”并保存 123347 并将“选项”保存到以下字符串中的字符串:
{
"type" : "radiobuttons",
"patient" : false,
"text" : "How are you today",
"id" : 63339,
"position" : 2,
"options" : "123344:ok today;123345:see you tomorrow;123346:call friend;123347:call lisa;",
"required" : true,
"choices" : {
"123347" : {
"value" : 3,
"option" : "iOS"
},
"123345" : {
"option" : "Android",
"value" : 1
},
"123346" : {
"option" : "Windows",
"value" : 2
},
"123344" : {
"option" : "MAC",
"value" : 0
}
}
}
let json = try? JSONSerialization.jsonObject(with: str, options: [])
解决方案
斯威夫特 5
尝试序列化和解码它
let jsonResponse = try JSONSerialization.data(withJSONObject: responseObject as Any, options: JSONSerialization.WritingOptions.sortedKeys)
let customObject = try JSONDecoder().decode(CustomObject.self, from: jsonResponse)
guard let requiredChoice = customObject.choices["123347"] else{
return
}
let option = requiredChoice.option
print(option)
您的 json 的 CustomObject:
struct CustomObject: Codable {
let type: String
let patient: Bool
let text: String
let id, position: Int
let options: String
let customObjectRequired: Bool
let choices: [String: Choice]
enum CodingKeys: String, CodingKey {
case type, patient, text, id, position, options
case customObjectRequired = "required"
case choices
}
}
struct Choice: Codable {
let option: String
let value: Int
}
有许多工具可以轻松地为您的 json 创建结构/类:例如:https ://app.quicktype.io
推荐阅读
- c# - 将列表作为输入参数的方法,其中每个项目都是不同的泛型类型
- python - Matplotlib 分组子图在集群之间添加空间
- vue.js - 加载 lottie-web 动画问题 vuejs
- sql - 从另一个表返回与第一个表中的值匹配的值
- python - Python - 当数字等于或高于问题时
- html - 如何在谷歌应用脚本中重构 HTML 表?
- javascript - 获取元素相对于页面的位置(HTML 文档)
- azure - Azure 应用服务解决方法 500 自定义域限制
- visual-studio-code - 如何为 PyRight 设置根目录?
- c# - 通知其他用户更改视图 C# 和 ASP.NET Core