首页 > 解决方案 > 如何将 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

标签: iosswiftiphone

解决方案


请使用 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
    }
}

推荐阅读