如何在swift iOS

时间:2017-07-07 07:31:46

标签: ios json swift

您好我是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()
    }
}

6 个答案:

答案 0 :(得分:5)

对于映射,您可以使用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"
    }
}]

和mapper类:

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)           
        }
    }
}

答案 1 :(得分:2)

第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
  }
 }
}

步骤2:按以下方式声明您的数组。

var myTargetArray = [Club]()

Step3:Json Parsing。

    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源。快乐的编码...

答案 2 :(得分:1)

您可以使用以下网址创建模型类:http://www.jsoncafe.com/

打开此链接,然后将json放在JSON选项卡中,然后选择所需的任何代码模板。如果需要,还可以添加前缀类名和根类名,否则它是可选的。最后单击“生成”按钮,您的json类就准备好了!!

答案 3 :(得分:0)

模特课:

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

答案 4 :(得分:0)

**使用模型类,swiftyjson和alamofire进行API调用,Pod安装alamofire和swiftyjson库,创建集合视图单元格类,创建一个类并编写以下代码 **

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
}}

答案 5 :(得分:0)

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

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