我必须在服务器上发布一些数据。数据的JSON结构如下。
"hospital": {
"hospitalId": "1212111",
"hospitalName": "xcxcxcx",
"address": {
"addressLine1": "fagsgsah",
"locality": {
"id": "",
"name": "",
"pLink": ""
},
"city": {
"id": "",
"name": "",
"pLink": ""
}
}
}
我可以轻松使用Dictionary来实现这种数据结构。但我已经读过创建模型是发布和解析数据的最佳实践。我创建了四个模型Hospital
,Address
,State
,City
以获得更大的灵活性。您可以在医院模型中看到,任何模型中都可能有更多属性。我的问题是如何实现给定的JSON结构,我可以将其作为参数传递给Alamofire。我是否应该根据数据要求在模型中write multiple initializer
?
import UIKit
class Hospital {
var hospitalId:String?
var hospitalName:String?
var address:Address?
var fee:Int?
var openingTime:UInt64?
var closingTime:UInt64?
}
/** Address **/
class Address {
var addressLine1:String?
var locality:Locality?
var city:City?
}
/** City **/
class City {
var cityId:String?
var cityName:String?
var cityPLink:String?
}
/** locality **/
class Locality {
var localityId:String?
var localityName:String?
var localityPLink:String?
}
答案 0 :(得分:1)
Almofire不支持将Modal类自动绑定到Response中。是的,您应该为每个模态类编写带有JSON数据的模态初始化器。
https://gist.github.com/jpotts18/e39ee74de84ae094b270提供了如何将Simple JSON,Collections和Nested JSON数据绑定到模态类的示例。
答案 1 :(得分:0)
尝试这可能会有所帮助。
import Foundation
class Hospitalmodel: NSObject {
var hospitalId:String!
var hospitalName:String!
var fee:Int!
var openingTime:UInt64!
var closingTime:UInt64!
var address:Address!
init(dict:NSDictionary){
if(dict["hospitalId"] != nil){
self.hospitalId = dict["hospitalId"] as! String
}
if(dict["hospitalName"] != nil){
self.hospitalName = dict["hospitalName"] as! String
}
if(dict["address"] != nil){
let send = dict["address"] as! NSDictionary
if send.allKeys.count>0{
self.address = Address.init(dict: send)
}
}
}
}
class Address {
var addressLine1:String!
var locality:Locality!
var city:City!
init(dict:NSDictionary)
{
if(dict["addressLine1"] != nil){
self. addressLine1 = dict["addressLine1"] as! String
}
if(dict["locality"] != nil){
let send = dict["locality"] as! NSDictionary
if send.allKeys.count>0{
self.locality = Locality.init(dict: send)
}
}
if(dict["city"] != nil){
let send = dict["city"] as! NSDictionary
if send.allKeys.count>0{
self.city = City.init(dict: send)
}
}
}
}
class Locality {
var localityId:String!
var localityName:String!
var localityPLink:String!
init(dict:NSDictionary)
{
if(dict["id"] != nil){
self.localityId = dict["id"] as! String
}
if(dict["name"] != nil){
self.localityName = dict["name"] as! String
}
if(dict["pLink"] != nil){
self.localityPLink = dict["pLink"] as! String
}
}
}
class City {
var cityId:String!
var cityName:String!
var cityPLink:String!
init(dict:NSDictionary)
{
if(dict["id"] != nil){
self.cityId = dict["id"] as! String
}
if(dict["name"] != nil){
self. cityName = dict["name"] as! String
}
if(dict["pLink"] != nil){
self.cityPLink = dict["pLink"] as! String
}
}
}
答案 2 :(得分:0)
我还没试过swift4 Codable,如果你使用swift4可以选择你,如果它是swift 3那么我会建议使用AlamofireObjectMapper
请看一下它真的很容易使用的例子。