【问题标题】:Problems parsing JSON with SwiftyJSON使用 SwiftyJSON 解析 JSON 的问题
【发布时间】:2018-03-25 17:51:40
【问题描述】:

我正在尝试使用SwiftyJSON 解析以下数据:

{
"state": {
    "on": true,
    "bri": 100,
    "alert": "none",
    "mode": "homeautomation",
    "reachable": true
},
"swupdate": {
    "state": "noupdates",
    "lastinstall": "2018-03-10T10:39:45"
},
"type": "Dimmable light",
"name": "Hue white lamp 1",
"modelid": "LWB010",
"manufacturername": "Philips",
"productname": "Hue white lamp",
"capabilities": {
    "certified": true,
    "control": {
        "mindimlevel": 5000,
        "maxlumen": 806
    },
    "streaming": {
        "renderer": false,
        "proxy": false
    }
},
"config": {
    "archetype": "classicbulb",
    "function": "functional",
    "direction": "omnidirectional"
},
"uniqueid": "00:17:99:f1:03:c4:0e:8b-2e",
"swversion": "1.29.0_r21169",
"swconfigid": "FF7681C5",
"productid": "Philips-LWB010-4-A19DLv4"
}

我成功地使用以下代码打印了整个数据:

let json = JSON(value)
print(json)

但是,每当我尝试访问内部结构时,我都会得到null;例如,

print(json["state"])
print(json["swupdate"])
print(json["swconfigid"])

接收数据的完整函数如下:

func getStatusRequest() {
    // getStatusRequest
    // retrieve current status of lamp-1

    Alamofire.request(url, parameters: authParameters).validate().responseJSON { response in
        switch response.result {

        // handle success
        case .success (let value):
            self.infoLabel.textColor = UIColor.green // change lable color
            self.infoLabel.text = "Connection established"

            let json = JSON(value)
            print(json)
            // PARSE JSON HERE



        // handle failure
        case .failure(let error):
            self.disableAll() // disable GUI
            self.infoLabel.textColor = UIColor.red // change lable color

            // print error message
            if let errorCode = response.response?.statusCode {
                switch errorCode {
                case 401: self.infoLabel.text = "[\(errorCode)] Unauthorised access."
                case 403: self.infoLabel.text = "[\(errorCode)] Access denied."
                case 502: self.infoLabel.text = "[\(errorCode)] Service down."
                default: self.infoLabel.text = "[\(errorCode)] Interal error."
                }
            }
            else {
                self.infoLabel.text = "[error] Server down."
                debugPrint("DEBUG: \(error)") // debug print
            }
        }
    }
}

我使用的是 Mac OS 10.13.3、Xcode 9.2 和 SwiftyJSON 4。我做错了什么?

【问题讨论】:

    标签: json swift xcode swift4 swifty-json


    【解决方案1】:

    如果源是一个字符串,你必须使用初始化器

    let json = JSON(parseJSON: value)
    

    初始化器

    public init(_ object: Any)
    

    不将 String 解析为 JSON,而是使用 init(parseJSON: String)

    注意:Swift 4 中的 Codable 协议使 SwiftyJSON 作为解析器过时了。

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多