【问题标题】:Weird json decoder behaviour奇怪的 json 解码器行为
【发布时间】:2018-07-08 05:04:25
【问题描述】:

所以,我有从通知中获得的 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

当代码到达 print("this is json data (dict)") 数据是没有问题的,但是当代码到达 print("this is status (dict[ "status"])") 它在日志上给出 null。您是否遇到过同样的问题?

【问题讨论】:

    标签: ios json swift decode swifty-json


    【解决方案1】:

    快速浏览一下 SwiftyJSON 文档会立即发现错误:

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

    public init(_ object: Any) {
    

    所以你必须使用

    let dict = JSON(parseJSON: data)
    

    【讨论】:

    • 它对我有用。但我确实有一个问题,为什么会这样?我在 API 调用中使用“JSON(res)”,它没有任何问题。
    • 但我必须将我的“数据”转换为带有“数据为!字符串”的字符串才能使用您的解决方案。顺便说一句,我从“func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)” 获得“数据”。
    • 为了明确一点:如果decodedNotificationTransactionData(data... 中的data 参数是Data,则使用JSON(data),但是在您的示例中显然是String,所以您必须使用JSON(parseJSON: data)
    • 好的,现在我了解导致问题的原因。非常感谢您的帮助和解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多