简体   繁体   中英

Swift to get result of array values from JSON

My scenario i have four labels in a view, I need to get result of marks value and assign to that labels.If I received only one index within array I need to call some other function. I am using old method JSON not codable and thirdparty lib. Please provide some solution.

Below, my response

{
    "status": 1,
    "status_code": 200,
    "result": [
        "100 marks",
        "30 marks",
        "40 marks",
        "70 marks"
    ]
}

Below code I am using

if (status_code != 200) {
    print("ERROR:\(String(describing: status_code))")
} else {
    let results = result["result"]  as? String
    print("Marks:\(results ?? "")")

    // Call confirmation alert
    DispatchQueue.main.async {
        self.one_label.text! = ""
        self.two_label.text! = ""
        self.three_label.text! = ""
        self.four_label.text! = ""
    }
}

The incorrect part of your code is: you are trying to cast result["result"] as a singular String , which is not! it is an array of strings. So what you should do is:

if let results = result["result"]  as? [String] {
    print(results[0]) // first mark in the array (100 marks)
}

Furthermore:

At this point, I would recommend to follow the approach of templating the data instead of dealing with dictionaries. Since have a valid Json, you can achieve it easily with Docadable protocol, Example:

let json = """
{
"status": 1,
"status_code": 200,
"result": [
"100 marks",
"30 marks",
"40 marks",
"70 marks"
]
}
""".data(using: .utf8)

struct Result: Decodable {
    var status: Int
    var statusCode: Int
    var result: [String]

    enum CodingKeys: String, CodingKey {
        case status
        case statusCode = "status_code"
        case result
    }
}

let decoder = JSONDecoder()
let resultObject = try decoder.decode(Result.self, from: json!)
print(resultObject)

The result in json is array. So you need to cast it to array.

let results = result["result"]  as? [String]
        print("Marks:\(results ?? "")")

The result has [String] so please

Replace

let results = result["result"]  as? String

to

   if let results = result["result"]  as? [String], results.count >= 4 {

    self.one_label.text! = results[0] ?? ""
    self.two_label.text! = results[1] ?? ""
    self.three_label.text! = results[2] ?? ""
    self.four_label.text! = results[3] ?? ""

    } else {
        // Call your function here
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM