How to populate an array with information from JSON File and calculate distance?

强颜欢笑 提交于 2019-11-29 17:25:52

I had been working on your question and this are my results,

First of all I recommend you to use one JSON framework such as SwiftyJSON but I don't use any because I don't know if you want to, so

first we need to load our json using this code

let pathForPlist = NSBundle.mainBundle().pathForResource("JSON", ofType: "json")!
let JSONData = NSData(contentsOfFile: pathForPlist)

after we need to parse this data and convert to JSONObject

let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

and convert to properly Objects using an initializer from Dictionary, note that we use NSJSONReadingOptions.MutableContainers because our json is an array of dictionaries

this is the full code, note that I define a class for your data type named ObjectShop to help with the calculation later

import UIKit
import MapKit

class ObjectShop
{
    var A1 = ""
    var B1 = ""
    var C1 = ""
    var D1 = ""

    init?(dict:[String:AnyObject])
    {
        A1 = dict["A1"] as! String
        B1 = dict["B1"] as! String
        C1 = dict["C1"] as! String
        D1 = dict["D1"] as! String
    }

    func getCoordenate2D() -> CLLocationCoordinate2D
    {
        return CLLocationCoordinate2D(latitude: Double(self.C1)!, longitude: Double(self.D1)!)
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let pathForPlist = NSBundle.mainBundle().pathForResource("JSON", ofType: "json")!
        let JSONData = NSData(contentsOfFile: pathForPlist)
        do
        {
            var objects = [ObjectShop]()
            let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
            print(JSONObject)
            for dic in JSONObject["People"] as! [[String:AnyObject]] {
                print(dic)
                let objc = ObjectShop(dict: dic)
                objects.append(objc!)
            }

            for object in objects {
                print(object.getCoordenate2D())
            }
        }
        catch _
        {

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

I hope this helps you, let me know if you have any question

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!