解析 JSON 文件(本地存储),从而快速创建对象数组

Posted

技术标签:

【中文标题】解析 JSON 文件(本地存储),从而快速创建对象数组【英文标题】:Parsing a JSON file(stored locally) and thus creating an array of objects in swift 【发布时间】:2015-10-10 07:27:35 【问题描述】:

我是 json 解析术语的初学者。我实际上是在尝试从本地存储在我的 swift 项目中的 json 文件中获取数据。我已经正确完成了所有事情,并且现在可以获取数据。但是,我无法创建对象数组(将根据来自 json 文件的值集创建对象)。然后在视图控制器(CompanyViewController.swift)类中使用该数组。我已经在另一个类中编写了我的 json 解析代码(此处为 CompanyHandler.swift ..),并且所有字段都已在另一个 swift 类中初始化(此处为 Company.swift ..)。

我的 CompanyViewController.swift 控制器文件如下:

class CompanyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout 

    @IBOutlet var collectionView: UICollectionView!

    override func viewDidLoad() 
        super.viewDidLoad()

        var customCollectionViewCell = CustomCollectionViewCell()

        collectionView.registerNib(UINib(nibName: "CustomCollectionViewCell", bundle:nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")
        collectionView!.multipleTouchEnabled = true
        collectionView!.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(collectionView!)
        AppEngine().getCompanyDetails()

    

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
        var cell = collectionView.cellForItemAtIndexPath(indexPath) as CustomCollectionViewCell
//        cell.customImageView?.image = UIImage(named: "\(array[indexPath.row])")
        AppEngine().getCompanyDetails()

//        if ((cell.selected) && (indexPath.row == 0)) 
//        var vc: AbcViewController = AbcViewController(nibName: "AbcViewController", bundle: nil)
//        self.navigationController?.pushViewController(vc, animated: true)
//        
    

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize 
        var abc = CGSize(width: collectionView.frame.size.width,height: collectionView.frame.size.height/2)
        return abc
    

    func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool 
        return true
    

    func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool 
        return true
    

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int 
        return 1
    

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
        return 15
    

    func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool 
        return true
    

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomCollectionViewCell", forIndexPath: indexPath) as CustomCollectionViewCell

        cell.customImageView?.image = UIImage(named: "image1.png")
        cell.customLabel?.text = "\(indexPath.row)"
        return cell
    

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



My Company.swift controller file is as following:

class Company 
    var companyID: String
    var companyName: String
    var companyAddress: String
    var companyWebAddress: String
    var companyFB_Address: String
    var companyTWT_Handle: String
    var companyLI_Address: String
    var aboutUs: String
    var email_ID: String
    var ivrNo: String
//    var projects: NSMutableArray = ["Project"]
//    var projectStatus: String

    init(companyID: String, companyName: String,companyAddress: String, companyWebAddress: String, companyFB_Address: String, companyTWT_Handle: String, companyLI_Address: String, aboutUs: String, email_ID: String, ivrNo: String)
    
        self.companyID = companyID
        self.companyName = companyName
        self.companyAddress = companyAddress
        self.companyWebAddress = companyWebAddress
        self.companyFB_Address = companyFB_Address
        self.companyTWT_Handle = companyTWT_Handle
        self.companyLI_Address = companyLI_Address
        self.aboutUs = aboutUs
        self.email_ID = email_ID
        self.ivrNo = ivrNo
//        self.projects = projects
//        self.projectStatus = projectStatus
    




My CompanyHandler.swift controller file is as following:

class CompanyHandler 

// MARK: - company details
    func getCompanyDetails() 



 var jsonPath = NSBundle.mainBundle().pathForResource("companyDetails", ofType: "json")
        var data = NSData(contentsOfFile: jsonPath!)
        var jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!,
            options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        var companyArray:NSArray = jsonData["companyDetails"] as NSArray!

        for i in companyArray
            var cmpID: String = i["companyID"] as String
            var cmpName: String = i["companyName"] as String
            var cmpAdd: String = i["companyAddress"] as String
            var cmpWebAdd: String = i["companyWebAddress"] as String
            var cmpfbAdd: String = i["companyFB_Address"] as String
            var cmptwtAdd: String = i["companyTWT_Handle"] as String
            var cmpliAdd: String = i["companyLI_Address"] as String
            var abtUs: String = i["aboutUs"] as String
            var emailId: String = i["email_ID"] as String
            var ivrNo: String = i["ivrNo"] as String
            println("\(ivrNo)")

        var company = Company(companyID: "cmpID", companyName: "cmpName", companyAddress: "cmpAdd", companyWebAddress: "cmpWebAdd", companyFB_Address: "cmpfbAdd", companyTWT_Handle: "cmptwtAdd", companyLI_Address: "cmpliAdd", aboutUs: "abtUs", email_ID: "emailId", ivrNo: "ivrNo")
        
    

【问题讨论】:

欢迎任何建议 【参考方案1】:

您实际上并没有创建一个公司对象数组,它将充当您的集合视图的数据源。您只是在初始化新的 Company 对象,但没有对它们做任何事情。在您的CompanyViewController 上创建一个属性并将其设为[Company] 类型。在您的 json 字典的每次迭代中,在您创建一个新公司后,将其附加到您的 Company 数组中,然后将该数组用于您的集合视图。

【讨论】:

实际上我无法创建一个对象并将其扔到 ComapanyViewController 类中的数组中。我也无法使用语法 var cmpID: AnyObject? = companyArray.objectAtIndex(i).objectForKey("companyID") as NSString 需要从这个函数返回一个数组

以上是关于解析 JSON 文件(本地存储),从而快速创建对象数组的主要内容,如果未能解决你的问题,请参考以下文章

Angular解析json

json常用方法和本地存储方法

解析大型 JSON 文件 [重复]

如何将对象存储在本地文件中?

通过忽略时区将 JSON DateTime 对象解析为 JQuery 中的本地时间

python json快速解析命令