【问题标题】:How to make model class for following JSON response in swift iOS如何在 Swift iOS 中为跟随 JSON 响应创建模型类
【发布时间】:2017-07-07 07:31:45
【问题描述】:

嗨,我是 swift ios 的初学者,我的要求是必须显示 Json 对表格列表的响应,我从 Web 服务得到响应,响应如下所示

我的要求是如何将该模型类映射到 Array 以及如何在 tableList 中显示它们,请有人帮助我

JsonResponse:-

[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]

映射:

俱乐部:-

class Club { 

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}

位置:-

class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}

NSURlSession 代码:-

class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}

【问题讨论】:

  • 你需要先解析这个json,然后保存到一个数组中。
  • 看起来不错,除了 var location 不是 JSON 中的数组。如果您想轻松映射,可以使用 ObjectMapper
  • 你能帮我如何使用 ObjectMapper 库来做到这一点,我是 swift 的新手
  • stackoverflow.com/questions/44922697/…。检查我的答案并按照它完全适合您的要求进行操作。
  • 你可以试试这个框架:github.com/SwiftyJSON/SwiftyJSON

标签: ios json swift


【解决方案1】:

对于映射,您可以使用 Alamofire 的扩展 ObjectMapper。

例如:

[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
    "city" : "Madrid"
}
}, {
    "_id" : "540b2ff281b30f3504a1c72f",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
    "name" : "Teatro Kapital",
    "hasVippler" : false,
    "location" : {
        "address" : "Atocha, 125",
        "city" : "Madrid"
    }
}, {
    "_id" : "540cd44581b30f3504a1c73b",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
    "name" : "Charada",
    "hasVippler" : false,
    "location" : {
        "address" : "La Bola, 13",
        "city" : "Madrid"
    }
}]

和映射器类:

import ObjectMapper

class Location: Mappable {
    var address: String?
    var city: String?

    required init?(map: Map){

    }

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

class Club: Mappable {
    var id: String?
    var imageUrl: Int?
    var name: String?
    var hasVip: Bool = false
    var location: Location?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        id <- map["_id"]
        imageUrl <- map["imageUrl"]
        name <- map["name"]
        hasVip <- map["hasVippler"]
        location <- map["location"]
    }
}

而且这种方式使用起来非常灵活和透明。

https://github.com/Alamofire/Alamofire https://github.com/tristanhimmelman/AlamofireObjectMapper

使用示例:

Alamofire.request(URL).responseArray { (response: DataResponse<[Club]>) in

    let clubs = response.result.value

    if let clubs = clubs {
        for club in clubs {
            print(club.name)
            print(club.location.city)           
        }
    }
}

【讨论】:

  • 如何将 WeatherResponse 添加到数组中,能否请您添加该代码?
  • let weatherResponseObject = WeatherResponse(JSONString: JSONString)
  • 我添加了使用示例
  • 嗨,Zaak,我正在使用 NSURlSeesion 与 Web 服务集成,并以 JSon 对象的形式得到结果,就像我的回复一样
  • 那为什么又是这一行 Alamofire.request(URL).responseArray { (response: DataResponse) in
【解决方案2】:

您可以使用此网址制作模型类:http://www.jsoncafe.com/

打开此链接并将您的 json 放入 JSON 选项卡并选择您想要的任何代码模板。如果您愿意,您还可以添加前缀类名和根类名,否则它是可选的。最后点击生成按钮,你的 json 类就准备好了。!!

【讨论】:

  • 控制器中如何使用生成类?
【解决方案3】:

第 1 步:创建您的模型,如下所示。

class Club { 
        var id: String = ""
        var name: String = ""
        var imageUrl: String = ""
        var hasVip: Bool = false
        var desc: String = ""
        var location = Location()

        init?(dictionary:[String:Any],location: Location) {
            guard let id = dictionary["_id"],
                let name = dictionary["name"],
                let imageUrl = dictionary["imageUrl"],
                let hasVip = dictionary["hasVippler"]
            else {
                return nil
            }
     self.id = id
     self.name = name
     self.imageUrl = imageUrl
     self.hasVip = hasVip
     self.location = location
  }
 }
}
class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""

   init?(dictionary:[String:Any]) {
            guard let country = dictionary["country"],
                let city = dictionary["city"],
                let address = dictionary["address"],
                let zip = dictionary["zip"]
            else {
                return nil
            }
     self.country = country
     self.city = city
     self.address = address
     self.zip = zip
  }
 }
}

第二步:如下声明你的数组。

var myTargetArray = [Club]()

Step3:Json 解析。

    do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                print("Response: \(json)")

            for club in json {
                   if let clubDictionary = club as? NSDictionary { 
                     if let locationDict = clubDictionary["location"] as? NSDictionary{
                         if let location = Location(dictionary: locationDict) {

                           if let clubObj = Club(dictionary: clubDictionary, location:location) {
                            myTargetArray.append(clubObj)
                       }
                   }
                }
            }
        }
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)// Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }

注意:我从位置模型中删除了地下阵列,因为您的 json 数据不包含它。 最后,您可以使用您的目标数组作为您的 tableview 源。快乐编码...

【讨论】:

  • 如果发生任何数据类型冲突,只需相应地进行类型转换。
  • 如果让 locationDict = club["location"] as? NSDictionary{ 显示错误的行
【解决方案4】:

模型类:

class test : Unboxable {
let id : String
let imageURl : String
let name : String
let hasVip : Bool
let city : String

required init(unboxer: Unboxer) throws {
    self.id = unboxer.unbox(key: "id") ?? ""
    self.imageURl = unboxer.unbox(key: "imageUrl") ?? ""
    self.name = unboxer.unbox(key: "name") ?? ""
    self.hasVip = unboxer.unbox(key: "hasVip") ?? false
    self.city = (unboxer.unbox(key: "city") ?? nil)!
}
}

解析json:

if let object = json as? [Any] {
                // json is an array

                var data :[test] = []
                for respObject in object {

                    var dict = respObject as? Dictionary<String,AnyObject>
                    dict?["city"] = dict?["location"]?["city"] as AnyObject
                     let result1: [test] = try unbox(dictionaries: [dict!])
                    data.append(contentsOf: result1)

                }

                print(data)

更多详情请关注 https://github.com/JohnSundell/Unbox

【讨论】:

    【解决方案5】:

    **Api调用模型类,swiftyjson和alamofire,Pod安装alamofire和swiftyjson库,创建collection view cell类,创建类并编写如下代码 **

    import UIKit
    import Alamofire
    import SwiftyJSON
    var myResponse : JSON? = nil
    var users : [reasonList] = []
    class HomeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
     feedbackApi()
    }
    
    func feedbackApi(){
        DispatchQueue.main.async {
            let url = URL(string: "--------")
            let urlRequest = URLRequest(url: url!)
            Alamofire.request(urlRequest)
                .responseJSON { response in
                    switch response.result{
                    case.success(let data):
                        print("dddd :",data)
                        self.myResponse = JSON(data)
                        print(self.myResponse as Any)
                        let a = self.myResponse![0]["reasonList"]
                        print(a)
                        for i in 0..<a.count{
                            let single = reasonList(reasonListJson: a[i])
                            self.users.append(single)
    
                        }
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    case .failure(let error):
                        print("dddd",error)
                    }  
            }
        }
    }
    

    }

    创建模型类

    import Foundation
    import SwiftyJSON
    
    class user{
    var deviceId = String()
    var deviceName = String()
    var deviceLocationId = Int()
    var locationName = String()
    var welcomeText = String()
    var reason=[reasonList]()
    init(userJson:JSON)  {
        self.deviceId = userJson["deviceId"].stringValue
         self.deviceName = userJson["deviceName"].stringValue
         self.deviceLocationId = userJson["deviceLocationId"].intValue
         self.locationName = userJson["locationName"].stringValue
         self.welcomeText = userJson["welcomeText"].stringValue
        self.reason = [reasonList(reasonListJson: userJson["reason"])]
    }}
    class reasonList{
    var reason = String()
    var id = Int()
    init(reasonListJson:JSON) {
        self.reason = reasonListJson["reason"].stringValue
        self.id = reasonListJson["id"].intValue
    ]}
    

    **在视图中创建一个集合视图**

    import UIKit
    import Alamofire
    import SwiftyJSON
    class ReasonViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
    override func viewDidLoad() {
        super.viewDidLoad()
        //DelayCall()
    
    
        // Do any additional setup after loading the view.
    }
    func DelayCall() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
            _ = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController")as! HomeViewController
            self.navigationController?.popViewController(animated: true)
        }
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return users.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReasonCollectionViewCell", for: indexPath) as! ReasonCollectionViewCell
        let useee = users[indexPath.row]
    
        print(useee)
       cell.reasonLabel.text = useee.reason
        return cell
    }}
    

    【讨论】:

      【解决方案6】:

      您可以使用此网址制作模型类:https://www.json4swift.com/

      打开此链接并粘贴您的 JSON,然后从下面的选项中选择您想要的。点击生成,它会生成类文件,你可以下载并在你的项目中使用。

      【讨论】:

        猜你喜欢
        • 2020-02-24
        • 1970-01-01
        • 2017-08-29
        • 1970-01-01
        • 2020-06-23
        • 2012-09-15
        • 2020-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多