在Swift中使用Alamofire解析JSON响应

时间:2014-10-07 14:07:34

标签: ios json swift alamofire

使用Alamofire Framework时,我的回复似乎没有被正确解析。我得到的JSON响应有一些看似不是字符串的键,我不知道如何引用它们/获取它们的值。

以下是我调用代码的部分:

var url = "http://api.sandbox.amadeus.com/v1.2/flights/low-fare-search"
var params = ["origin": "IST", 
         "destination":"BOS", 
      "departure_date":"2014-10-15", 
   "number_of_results": 1, 
              "apikey": KEY]

Alamofire.request(.GET, url, parameters: params)
  .responseJSON { (_, _, json, _) in
    println(json)
  }
}

以下是调用该函数时的第一部分打印输出

Optional({
  currency = USD;
  results = ({
      fare = {
        "price_per_adult" = {
          tax = "245.43";
          "total_fare" = "721.43";
        };
        restrictions = {
          "change_penalties" = 1;
          refundable = 0;
        };
        "total_price" = "721.43";
      };
    ...
  });
});

您会注意到results不是"results",但"price_per_adult"是正确的格式。我缺少一些步骤吗?当我把它转换为NSDictionary时,它也没有做任何事情来帮助键格式。

我也在javascript和ruby中尝试了相同的端点,并且两者都没有问题,所以我相信它不是导致问题的API。

1 个答案:

答案 0 :(得分:2)

这些密钥仍为String,这就是Dictionary的{​​{1}} d。println。只有当它包含非字母数字字符(在这种情况下为String)时,它才会在打印时围绕_引号括起来。您可以通过手动创建与您从API请求中获取的Dictionary类似的let test = [ "currency": "USD", "results": [ [ "fare": [ "price_per_adult": [ "tax": "245.43", "total_fare": "721.43" ], "restrictions": [ "change_penalties": 1, "refundable": 0 ], "total_price": "721.43" ] ] ] ] println(test) 进行测试,然后将其打印出来:

{
    currency = USD;
    results = (
    {
            fare = {
                "price_per_adult" = {
                    tax = "245.43";
                    "total_fare" = "721.43";
                };
                restrictions = {
                    "change_penalties" = 1;
                    refundable = 0;
                };
                "total_price" = "721.43";
            };
        }
    );
}

输出:

{{1}}