使用SwiftyJSON解析JSON时出现问题

时间:2018-03-25 17:51:41

标签: json swift xcode swift4 swifty-json

我正在尝试使用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.我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果源是字符串,则必须使用初始化程序

let json = JSON(parseJSON: value)

初始化程序

public init(_ object: Any)
  

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

注意:Swift 4中的Codable原型协议使得SwiftyJSON作为解析器已经过时。