从JSON Parse返回数据 - Swift

时间:2017-02-25 17:12:36

标签: ios json swift

所以我是Swift的新手,而且有点编程。我从今年第一天起才开始这样做......我正在尝试创建一个从外部JSON文件中提取数据的简单应用程序,并将其输入到UILabels中。我已经获取了数据,并附加到数组中。从这里开始,它似乎退出了范围而在其他任何地方都无法使用......我已经创建了一个用于保存数据的结构。正如您所看到的,我已经添加了打印标记,以便直观地了解正在发生的事情。

  struct GlobalTestimonialData {
        var testimonialsText: [String]
        var customerNames: [String]
        var companyNames: [String]
    }

    var TestimonialData = GlobalTestimonialData(testimonialsText: [""], customerNames: [""], companyNames: [""])

    func getData () {
        let requestURL: URL = URL(string: "https://szadydesigns.com/test/mobileapp/testimonials.php")!
        let urlRequest = URLRequest(url: requestURL as URL) 
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in

            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode

    if (statusCode == 200) {
                print("File has been downloaded!")
                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)

                    print("JSON Serialized")

                    if let JSONfile = json as? [String: AnyObject] {
                        print("JSON Reading")
                        if let testimonial = JSONfile["testimonial"] as? [String] {
                            print("Testimonials Read")
                            TestimonialData.testimonialsText.append(contentsOf: testimonial)
                            print(TestimonialData.testimonialsText)
                            print("Inside of loop Testimonial Text Number: \(TestimonialData.testimonialsText.count)")

                            if let name = JSONfile["name"] as? [String] {
                                print("Names Read")
                                TestimonialData.customerNames.append(contentsOf: name)
                                print(TestimonialData.customerNames)
                                print("Inside of loop Customers Number: \(TestimonialData.customerNames.count)")
                            }
                            if let company = JSONfile["company"] as? [String] {
                                print("Companies Read")
                                TestimonialData.companyNames.append(contentsOf: company)
                                print(TestimonialData.companyNames)
                            }
                            print("Companies: \(TestimonialData.companyNames)")
                        }
                        print("COMPANIES: \(TestimonialData.companyNames)")
                    }
                    print("Companies AGIAN: \(TestimonialData.companyNames)")
                }catch {
                    print("Error with Json: \(error)")
                }
                print("Companies AGIAN AGAIN : \(TestimonialData.companyNames)")
            }
            print("Companies AGIAN AGAIN AGAIN: \(TestimonialData.companyNames)")
        }

        //Loses Scope
        print("Companies AGIAN TIMES : \(TestimonialData.companyNames)")
        task.resume()

        print("Outside of loop Customers Number: \(TestimonialData.customerNames.count)")
        print("Outside of loop Testimonial Text Number: \(TestimonialData.testimonialsText.count)")
        print(TestimonialData.companyNames)
    }

我知道我错过了一些非常简单的事情......但我感到很茫然...感谢任何帮助/信息!

1 个答案:

答案 0 :(得分:0)

此代码存在一些问题:

首先:您收到的JSON不符合您的代码所期望的格式。根对象不是字典而是数组。

if let JSONfile = json as? [String: Any] {

更改为

if let JSONfile = json as? [[String: String]] {

这也要求你循环每个项目。

print("JSON Reading")
for item in JSONfile {

由于字典定义已从[String:Any]更改为[String:String],因此不再需要as? String语句。

第二:我不确定你是否意识到这一点(也许你已经意识到了),但//Loses Scope行之后的代码位先运行 。在Companies AGIAN AGAINCompanies AGIAN AGAIN AGAIN行之前。

它们可能位于页面的下方,但上面的行位于文件下载后运行的闭包中,因此在其他行已经运行之后执行。

这是完整的固定代码(以这种方式格式化,您可以将其复制并粘贴到Xcode Playground中以查看它是否正常工作)。

// Xcode 8.2, Swift 3
import Cocoa
import PlaygroundSupport

// Required for the download to work.
PlaygroundPage.current.needsIndefiniteExecution = true


struct GlobalTestimonialData {
    var testimonialsText: [String]
    var customerNames: [String]
    var companyNames: [String]
}

var testimonialData = GlobalTestimonialData(testimonialsText: [], customerNames: [], companyNames: [])

func getData () {
    let requestURL: NSURL = NSURL(string: "https://szadydesigns.com/test/mobileapp/testimonials.php")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) in

        let httpResponse = response as! HTTPURLResponse
        let statusCode = httpResponse.statusCode
        if (statusCode == 200) {
            print("File has been downloaded!")
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)

                print("JSON Serialized")

                if let JSONfile = json as? [[String: String]] {
                    print("JSON Reading")
                    for item in JSONfile {
                        if let testimonial = item["testimonial"] {
                            testimonialData.testimonialsText.append(testimonial)

                            if let name = item["name"] {
                                testimonialData.customerNames.append(name)
                            }
                            if let company = item["company"] {
                                testimonialData.companyNames.append(company)
                            }
                        }
                    }
                }
            } catch {
                print("Error with Json: \(error)")
            }
        }
        print("Companies Last: \(testimonialData.companyNames)")
        print(" ")
        print(testimonialData)
    }

    //Loses Scope
    print("Companies 1 : \(testimonialData.companyNames)")
    task.resume()

    print("Before the download of the JSON Customer names count: \(testimonialData.customerNames.count)")
    print("Before the download of the JSON Testimonial Text Number: \(testimonialData.testimonialsText.count)")
    print(testimonialData.companyNames)
}

getData()

你会得到这个输出,这有助于解释发生了什么(虽然我删除了实际的公司名称)。

Companies 1 : []
Before the download of the JSON Customer names count: 0
Before the download of the JSON Testimonial Text Number: 0
[]
File has been downloaded!
JSON Serialized
JSON Reading
Companies: ["REMOVED_1", "REMOVED_2", "REMOVED_3", "REMOVED_4"]