【问题标题】:Parse Alamofire result swift快速解析 Alamofire 结果
【发布时间】:2020-12-08 09:25:37
【问题描述】:

在 Swift 中解析来自 AF 请求的以下响应 – let json = result as! NSDictionary – 我非常迷茫:

{
    errors =     (
    );
    get = statistics;
    parameters =     {
        country = germany;
    };
    response =     (
                {
            cases =             {
                "1M_pop" = 14303;
                active = 317167;
                critical = 4179;
                new = "+15161";
                recovered = 863300;
                total = 1200006;
            };
            continent = Europe;
            country = Germany;
            day = "2020-12-08";
            deaths =             {
                "1M_pop" = 233;
                new = "+380";
                total = 19539;
            };
            population = 83900328;
            tests =             {
                "1M_pop" = 347331;
                total = 29141172;
            };
            time = "2020-12-08T09:15:08+00:00";
        }
    );
    results = 1;
}

知道如何获取实际案例编号,例如new 案例的数量吗?

到目前为止,我已经尝试了以下(错误抛出)方法:

if let responseDict = result as? NSDictionary {
                            if let data = responseDict.value(forKey: "response") as?
                                [NSDictionary] {
                                
                                // Get case numbers
                                guard let cases = data[0]["cases"] else { return }
                                guard let casesPerOneMil = cases[0] as! Int else { return }
                                print(casesPerOneMil)
                            }
                        }

【问题讨论】:

  • 有什么尝试吗?你知道字典和数组是如何工作的吗?如何使用键访问字典的值?如果是,JSON 只是 Dictionary、Array、String、Numbers(和 null)。所以从let response = json["response"] 开始(这是一个响应数组)。等等。但是,Codable 可能是一个好主意。
  • 对不起 - 已经包含了我迄今为止在问题中尝试过的内容!
  • 要调试,你需要知道casesnil? casesPerOneNil 是零吗?甚至抛出一个错误来崩溃(我不会使用as!,而是as?),如果是这样,错误信息是什么?但显然casesDictionary 而不是数组。所以cases[0] 应该会崩溃并在控制台中给出预期的错误消息。它应该是cases["1M_pop"]
  • guard let casesPerOneMil = cases["1M_pop"] as! Int else { return } 返回Value of type 'Any' has no subscripts

标签: swift alamofire nsdictionary swifty-json


【解决方案1】:

在 Swift 中基本上不要使用 NS... 集合类型,使用原生类型。
并且不要使用value(forKey,使用密钥订阅。

您必须有条件地将Any 转换为预期的具体类型。

还有一个错误:cases 的对象是一个字典,注意{} 并且您也必须通过键订阅获取casesPerOneMil 的值

if let responseDict = result as? [String:Any], 
   let dataArray = responseDict["response"] as? [[String:Any]],
   let firstDataItem = dataArray.first {
        
        // Get case numbers
        guard let cases = firstDataItem["cases"] as? [String:Any] else { return }
        guard let casesPerOneMil = cases["1M_pop"] as? Int else { return }
        print(casesPerOneMil)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2014-10-14
    相关资源
    最近更新 更多