如何在xcode中解析和分类来自AlamoFire的JSON响应

时间:2016-03-25 05:36:10

标签: ios arrays json swift http

我正试图从这个网站获得NBA排名https://erikberg.com/api 为此,我使用AlmoFire发出Get请求:

Alamofire.request(.GET, "https://erikberg.com/nba/standings.json") .responseJSON { response in print(response.2.value) }

返回的是一个响应数组,在索引0处有一个NSURLRequest,在索引1处有一个NSHTTPURLResponse,在索引2处有一个AnyObject类型的结果.AnyObject在打印时导致这个(我只显示一个)团队,因为数组很长):

Optional({ standing = ( { "away_lost" = 14; "away_won" = 21; conference = EAST; "conference_lost" = 13; "conference_won" = 29; division = CEN; "first_name" = Cleveland; "games_back" = 0; "games_played" = 71; "home_lost" = 6; "home_won" = 30; "last_five" = "4-1"; "last_name" = Cavaliers; "last_ten" = "7-3"; lost = 20; "ordinal_rank" = 1st; "playoff_seed" = 1; "point_differential" = 437; "point_differential_per_game" = "6.2"; "points_against" = 6948; "points_allowed_per_game" = "97.9"; "points_for" = 7385; "points_scored_per_game" = "104.0"; rank = 1; streak = W2; "streak_total" = 2; "streak_type" = win; "team_id" = "cleveland-cavaliers"; "win_percentage" = ".718"; won = 51; },exc...

我想知道如何解析这些数据,以便我可以根据他们的排名对每个团队进行提取和分类。 谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用ObjectMapper来解析JSON。创建一个包含所有JSON到对象映射代码的Standing类。

<body>

同样,让父类保持数组。

class Standing: Mappable {
    var awayLost: Int?
    var awayWon: Int?
    .....      // Define all variables
    required init?(_ map: Map) {}

    // This function is used to map all variables to corresponding JSON strings
    func mapping(map: Map) {      
         awayLost <- map["away_lost"]
         awayWon <- map["away_won"]
         ... 
    }

然后在你的alamofire回复中,映射相应的类

class ParentJson: Mappable {
    var standingsDate: String?
    var standing: [Standing]
}

func mapping(map: Map) {
    standing <- map["standing"]
}

standingArray现在将拥有分类所需的所有数据。

答案 1 :(得分:-1)

我使用SwiftyJSON包来解决与JSON相关的所有问题。然后,你可以使用这个成语

.responseJSON { response in
    switch response.result {
    case .Success:
        if let value = response.result.value {
            let json = JSON(value)
            if let datum = json["field"].string { // Depending on expected type; see docs

            }

     case .Failure(let error):
         print(error)
     }