簡體   English   中英

從JSON解析返回數據-Swift

[英]Returning Data from JSON Parse - 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)
    }

我知道我缺少一些非常簡單的內容...但是我很茫然...任何幫助/信息都非常感謝!

此代碼存在一些問題:

第一:您收到的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 as? String語句也不再需要。

第二:我不確定您是否意識到這一點(也許您已經意識到),但是//Loses Scope行之后的代碼位首先運行。 Companies AGIAN AGAIN Companies AGIAN AGAIN 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"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM