简体   繁体   English

如何从 iOS Swift 中的 JSON 响应中获取数据?

[英]How to get data from JSON response in iOS Swift?

Here i have using swiftyJson pod library for response data.在这里,我使用 swiftyJson pod 库来获取响应数据。 normal json response data i could able to get data but for complex i could not make it.普通的 json 响应数据我可以获取数据,但对于复杂的我无法获取。

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在 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:这是我的 json 响应:

{
"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从 json 响应中,我正在尝试获取WorkOrderDescription

Any help much appreciated pls....任何帮助非常感谢请....

Please read the JSON carefully.请仔细阅读 JSON。 The outermost object is a dictionary with a key d .最外面的对象是一个带有键d的字典。

To get the results array you have to write要获得results数组,您必须编写

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而你并不需要一个类,从来没有声明属性IUO这是在初始化init方法

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 .旁注:自从 Swift 4 SwiftyJSON已经过时,取而代之的是Codable It's built-in and much more efficient.它是内置的,而且效率更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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