Swift iOS : 解析json

RecoReco發表於2019-02-20

典型的前臺後臺的互動操作,幾乎都是這樣的:

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

使用Alamofire,它的擴充套件AlamofireObjectMapper可以把HTTP訪問獲得的結果轉換為json物件,使用ObjectMapper可以把json物件和swift物件做一個對映。

如下案例,訪問cnodejs.org提供的API,並轉換返回json為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"]
    }
}複製程式碼

如果列印結果形如:

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

說明程式碼正常運作。

相關文章