如何从JSON IN SWIFT初始化

时间:2018-03-22 06:57:17

标签: ios json

我有一个api ex: -

{data:[{name:a,location:{city:h}},{}],a:{},b:{}}

这是模式。我正在开发这种mvvm方法。

所以我为这个

创建了一个模型

我给出的是: -

var city:string!

var name:string!

我需要从中获取值。

前:

init?(dictionary :JSONDictionary) {

            guard let name = dictionary["name"] as? String,
                let description = dictionary["description"] as? String else {
                    return
            }

            self.name = name
            self.description = description
        }
下面的

就是一个例子。那么如何使用swift

获得模型中的最高价值

示例示例: - hostelmodel

class hostelmodel{



        var name :String!
        var description :String!

        init?(dictionary :JSONDictionary) {

            guard let name = dictionary["name"] as? String,
                let description = dictionary["description"] as? String else {
                    return
            }

            self.name = name
            self.description = description
        }



}
在hotelviewmodel中的

: -

 class hostelviewmodel:NSObject{


        var datasourceModel:DataSourceModel

        init(withdatasource  newDatasourceModel:DataSourceModel) {
            datasourceModel = newDatasourceModel
        }


        func datafordisplay(atindex index: Int) -> hostelmodel {
          return  datasourceModel.dataListArray![index]

        }

    }
DataSourceModel中的

: -

class DataSourceModel: NSObject {

    var dataListArray:Array<hostelmodel>? = []


    init?(array :Array<[String:Any]>) {

        var datalist:Array<hostelmodel> = []
        for dict in array{

            let model = hostelmodel(dictionary: dict)

            datalist.append(model!)
        }
        self.dataListArray = datalist        
}
}

在hostelview: -

 private var HOSTELMODEL :hostelmodel!

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, withViewModel viewModel:hostelviewmodel) {

        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        HOSTELMODEL = viewModel
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

我不知道tableview数据源应该提供什么... ... ...

最后是webservice类: -

private var url = URL(字符串:&#34; https://example.com&#34;)! typealias JSONDictionary = [String:Any]

class WebService{

    func loadFlowers(completion :@escaping ([hostelmoddel]) -> ()) {

        URLSession.shared.dataTask(with: url) { data, _, _ in

            if let data = data {

                let json = try! JSONSerialization.jsonObject(with: data, options: [])
                let dictionaries = json as! [JSONDictionary]

                let model = DataSourceModel(array: <#T##Array<[String : Any]>#>)

                DispatchQueue.main.async {
                    completion(dictionaries.flatMap(hostelmodel.init))
                }

            }

            }.resume()

    }





}

这段代码没有完全完成。所以这就是模式。所以如何获取值并在tableview中显示值。它必须在mvvm方法中,它不应该使用storyboard。怎么办。< / p>

1 个答案:

答案 0 :(得分:0)

如果你可以遍历“data”数组中的值,那么你正在寻找的类结构是这样的:

    class ModelName {
        var name: String?
        var city: String?

        init(_ dictionary: Dictionary<String, Any>) {
            if let name = dictionary["name"] as? String, let location = dictionary["location"] as? [String: Any], let city = location["city"] as? String {
                self.name = name
                self.city = city
            }
        }
    }

    class BusinesLogic {
        var dataList: [ModelName]?

        func getList() -> [ModelName]? {
            return dataList
        }

        func initializeData(_ rawDataArray: [[String : Any]]) {
            rawDataArray.forEach { rawData in
                dataList?.append(ModelName.init(rawData))
            }
        }
    }

// so to use:

    let sample = BusinesLogic()
    sample.initializeData([DATA ARRAY HERE])
    sample.getList()