如何从iOS Swift中的JSON响应中获取数据? [英] How to get data from JSON response in iOS Swift?

查看:324
本文介绍了如何从iOS Swift中的JSON响应中获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用swiftyJson Pod库获取响应数据。普通的json响应数据我可以获取数据,但是对于复杂的我却无法获取。

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()
}

在viewController.swift中使用了此功能

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()
            }
        }
    }
}

模型类:

import SwiftyJSON

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

这是我的json响应:

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"
            },
    }
}

从json响应中,我试图获取 WorkOrder 说明

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

任何帮助都值得赞赏....

Any help much appreciated pls....

推荐答案

请仔细阅读JSON。最外面的对象是带有键 d 的字典。

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 { ...

您不需要上课,并且永远不需要 strong>将属性声明为IUO,并使用 init 方法初始化

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
    }
}

侧面说明:自Swift 4 SwiftyJSON 变得过时,开始支持 Codable 。它是内置的,效率更高。

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

这篇关于如何从iOS Swift中的JSON响应中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆