简体   繁体   中英

How to get data from JSON response in iOS Swift?

Here i have using swiftyJson pod library for response data. normal json response data i could able to get data but for complex i could not make it.

here is my code to get data from response:

private func makeHTTPGetRequest(path: String, onCompletion: @escaping ServiceResponse) {

    let user = "David****"
    let password = "**************"
    let loginString = "\(user):\(password)"
    guard let loginData = loginString.data(using: String.Encoding.utf8) else {
        return
    }
    let base64LoginString = loginData.base64EncodedString()
    print("base 64 login :\(base64LoginString)")
    let headers = ["Authorization": "Basic \(base64LoginString)"]
    // using URL and request getting a json
    let request = URLRequest(url: NSURL(string: path)! as URL)
    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = headers
    let session = URLSession.init(configuration: config)
    session.dataTask(with: request) { (data:Data?, response: URLResponse?, error:Error?) in
        if let jsonData = data { // if data has a data and success
            do {
                let json: JSON = try JSON(data: jsonData)
                onCompletion(json,nil)
                print("json data:\(json)")
            }catch {// error
                onCompletion(JSON(),error)
            }
        } else { // if the data is nil
            onCompletion(JSON(),error)
        }
        }.resume()
}

Used this function in viewController.swift

func addDummyData() {
    // Call API
    RestApiManager.sharedInstance.getRandomUser { (json:JSON) in
        // return json from API
        if let results = json["results"].array { // get results data from json
            print("results:\(results)")
            for entry in results { // save data to items.
                self.items.append(UserObject(json: entry))
            }
            print("array= \(self.items)")
            DispatchQueue.main.async { // back to the main que and reload table
                self.tableView.reloadData()
            }
        }
    }
}

Model class:

import SwiftyJSON

class UserObject {
    //    var pictureURL: String!
    var username: String!
    required init(json: JSON) {
        //        pictureURL = json["picture"]["medium"].stringValue
        username = json["WorkOrder"].stringValue
    }
}

Here is my json response:

{
"d": {
    "results": [
            {
                "__metadata": {
                "id": "http://*******:****/sap/opu/odata/sap/ZPRJ_PM_APPS_IH_SRV/WorkOrderF4Set('000000504780')",
                "type": "ZPRJ_PM_APPS_IH_SRV.WorkOrderF4"
                },
    "WorkOrder": "000000504780",
    "Description": "General Maintenance testing"
            },
    }
}

From json response i'm trying to get WorkOrder and Description

Any help much appreciated pls....

Please read the JSON carefully. The outermost object is a dictionary with a key d .

To get the results array you have to write

if let results = json["d"]["results"].array { ...

And you don't need a class and never declare properties as IUO which are initialized in an init method

struct User {
    let workOrder: String
    let description: String

    init(json: JSON) {
        workOrder = json["WorkOrder"].stringValue
        description = json["Description"].stringValue
    }
}

Side note: Since Swift 4 SwiftyJSON has become obsolete in favor of Codable . It's built-in and much more efficient.

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