奇怪的json解码器行为

时间:2018-01-29 13:24:19

标签: ios json swift decode swifty-json

所以,我有来自通知的userInfo数据,我想解码并将这些数据传递给另一个类。我使用swiftyJSON作为json解码器。这是我的代码:

func decodedNotificationTransactionData(data: Any, completionHandler: @escaping (_ dict: [String : Any]) -> ()){

    let dict = JSON(data)

    print ("this is json data \(dict)")
    print("this is status \(dict["status"])")

    let test = [
        "id" : "\(dict["id"])",
        "orderDate" : "\(dict["orderDate"])",
        "patientName" : "\(dict["patient"]["fullName"])",
        "patientAddress" : "\(dict["patient"]["address"])",
        "caregiverName" : "\(dict["care"]["fullName"])",
        "caregiverAddress" : "\(dict["care"]["address"])",
        "serviceType" : "\(dict["service"]["label"])",
        "status" : "\(dict["status"])",
        "price" : "\(dict["totalAmount"])",
        "otherNote" : "\(dict["otherNote"])",
        "totalService" : dict["detailDatas"].count,
        "serviceLongType" : dict["detailDatas"][0]["type"],
        "jsonContent" : dict
        ] as [String : Any]

    completionHandler(test)

}

this the "print ("this is json data (dict)")" result

json data

当代码到达打印("这是json数据(字典)")时,数据没有问题,但代码达到打印(& #34;这是状态(dict [" status"])")它在日志上给出null。你有没有经历过同样的问题?

1 个答案:

答案 0 :(得分:3)

快速查看SwiftyJSON文档会立即显示错误:

  

创建一个JSON对象       - 参数对象:对象       - 注意:这不会将String解析为JSON,而是使用init(parseJSON: String)
      - 返回:创建的JSON对象

public init(_ object: Any) {

所以你必须使用

let dict = JSON(parseJSON: data)