Swift iOS : 解析json

典型的前臺後臺的交互操做,幾乎都是這樣的:node

  1. 訪問後臺服務API
  2. 而後解析它返回的JSON

使用Alamofire,它的擴展AlamofireObjectMapper能夠把HTTP訪問得到的結果轉換爲json對象,使用ObjectMapper能夠把json對象和swift對象作一個映射。json

以下案例,訪問cnodejs.org提供的API,並轉換返回json爲swift對象,而且打印驗證:swift

import UIKit
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,URLSessionDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        foo()
        return true
    }
    func foo(){
        let URL = "https://cnodejs.org/api/v1/topics?page=2"
        Alamofire.request(URL).responseObject { (response: DataResponse<Topics>) in

            let topics = response.result.value
            print(topics?.success)
            print(topics?.data?.count)
            if let item = topics?.data {
                for it in item {
                    print(it.id)
                    print(it.author?.avatar_url)
                    print(it.tab)
                    return
                }
            }
        }
    }
}
class Topics: Mappable {
    var success: Bool?
    var data : [Topic]?
    required init?(map: Map){

    }

    func mapping(map: Map) {
        success <- map["success"]
        data <- map["data"]
    }
}
//content title last_reply_at good top reply_count visit_count create_at author{loginname,avatar_url}
class Author : Mappable{
    var loginname: String?
    var avatar_url: String?
    required init?(map: Map){

    }
    func mapping(map: Map) {
        loginname <- map["loginname"]
        avatar_url <- map["avatar_url"]
    }
}
class Topic: Mappable {
    var id: String?
    var author_id : String?
    var tab : String?
    var content : String?
    var title : String?
    var last_reply_at : String?
    var good : String?
    var top : String?
    var reply_count : String?
    var visit_count : String?
    var create_at : String?
    var author : Author?
    required init?(map: Map){

    }
    func mapping(map: Map) {
        id <- map["id"]
        author_id <- map["author_id"]
        content <- map["content"]
        title <- map["title"]
        last_reply_at <- map["last_reply_at"]
        good <- map["good"]
        top <- map["top"]
        reply_count <- map["reply_count"]
        visit_count <- map["visit_count"]
        create_at <- map["create_at"]
        author <- map["author"]
        tab <- map["tab"]
    }
}複製代碼

若是打印結果形如:api

Optional(true)
Optional(40)
Optional("5989cd6c2d4b0af475035399")
Optional("59603478a4de5625080fe1cd")
Optional("ask")複製代碼

說明代碼正常運做。bash

相關文章
相關標籤/搜索