ios - 如何将 Json 值添加到模型数组中以快速显示到 tableview
问题描述
我正在使用 tableview 来显示两个 Json 值,但问题是我无法将值添加到模型结构中以使用两个 Api 显示到 tableview 中。我想在其中一个单元格标签中显示百分比值,这是我的 json
[
{
"Percentage": 99.792098999,
}
]
我的第二个 json 值
{
"Categories": [
"Developer",
"ios "
],
"Tags": [
{
"Value": "kishore",
"Key": "Name"
},
{
"Value": "2",
"Key": "office"
},
]
}
我需要在表格视图的类别标签中显示类别值
tableview 上的值和键
这是我的结构
struct info: Decodable {
let Categories: String?
let Tags: String?
let Value: String?
let Key: String?
var Name: String?
let percentage: Double?
}
这是我的代码
var List = [info]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
print(json as Any)
guard let jsonArray = json as? [[String: Any]] else {
return
}
print(jsonArray)
for dic in jsonArray{
guard let per = dic["percentage"] as? Double else { return }
print(per)
}
和第二个json
if let array = json["Tags"] as? [[String: String]] {
for dict in array {
let key = dict["Key"]
let value = dict["Value"]
switch key {
case "office":
case "Name":
default:
break;
}
}
这是我的行索引路径单元格
cell.Categories.text = list[indexpath.row].percentage
cell.Name.text = list[indexpath.row].name
cell.office.text = list[indexpath.row].office
解决方案
请使用 Swift 4 Codable 协议来解码来自 JSON 的值。
//1.0 Create your structures and make it conform to Codable Protocol
struct Tags: Codable{
var Key: String
var Value: String
}
struct Sample: Codable{
var Categories: [String]
var Tags: [Tags]
}
在您的方法中,执行以下步骤:
//2.0 Get your json data from your API. In example below, i am reading from a JSON file named "Sample.json"
if let path = Bundle.main.path(forResource: "Sample", ofType: "json") {
do {
let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
do {
//3.0 use JSONDecoder's decode method to decode JSON to your model.
let sample = try JSONDecoder().decode(Sample.self, from: jsonData)
//4.0 User the "sample" model to do your stuff. Example, printing some values
print("Sample.Category = \(sample.Categories)")
print("Sample.Name = \(sample.Tags[0].Value)")
print("Sample.Office = \(sample.Tags[1].Value)")
} catch let error {
print("Error = \(error)")
}
} catch {
// handle error
}
}
推荐阅读
- r - 无法让 kmeans 工作?
- node.js - Google Cloud Node js 部署问题:(gcloud.app.deploy)错误响应:[9]
- r - 闪亮的 renderUI 元素不会缩放到较小的屏幕
- javascript - 来自另一个 div 中的图像的动态缩略图
- excel - Excel 数字格式,仅在必要时显示小数
- kubernetes - 编辑 /etc/kubernetes/manifests/kube-apiserver.yaml 后 kube-apiserver 如何重启
- jquery - 包含键和值时返回未定义的数组长度
- html - 子菜单被隐藏
- python - python openweather包不起作用
- scala - DataFrame 写入速度比 RDD 慢 10 倍,在 spark 中保存到 cassandra