如何在JSONSerialization.jsonObject函数中使用utf8 - swift

时间:2017-08-08 11:27:26

标签: ios json swift xcode

我收到了这个错误:

  

致命错误:在展开Optional值时意外发现nil   2017-08-08 13:36:37.343479 + 0430 ostadcat [6976:1695644]致命错误:   在展开可选值时意外发现nil

我正在使用此功能连接到服务器:

func getFirstPageApplication(EMPTY:String,completionHandler: @escaping (_ response: AnyObject) -> ())
    {
        var strResponse = "null"
        var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
        request.httpMethod = "POST"
        let postString = "EMAIL=\(EMPTY)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                DispatchQueue.main.async {
                    completionHandler({} as AnyObject)
                }

            } else {

                var mdata = String(data: data!, encoding: .utf8)
                var mmdata = mdata?.data(using: String.Encoding.utf8, allowLossyConversion: false)!
                if let usableData = mmdata {
                    do {

                        let jsonResult = try JSONSerialization.jsonObject(with: usableData, options:
                            JSONSerialization.ReadingOptions.mutableContainers)
                        //print("worked")
                        //print(jsonResult) //this part works fine
                        DispatchQueue.main.async {
                            completionHandler(jsonResult as AnyObject)
                        }

                    } catch {
                        DispatchQueue.main.async {
                            completionHandler({} as AnyObject)
                        }
                        print("JSON Processing Failed")
                    }
                }
            }
        }
        task.resume()

    }

我的回复是JSON值,其内容包含UTF8字符集。

输出值与JSON不同,因为我收到的JSON不是UTF8格式,所以我得到了nil。 如何使用UTF8执行此功能:JSONSerialization.jsonObject

mdata的输出:

Optional("{\"sliders\":[{\"id\":4,\"title\":\"\\u0647\\u0645\\u06cc\\u0634\\u0647 \\u0628\\u0647 \\u0622\\u0648\\u0627\\u0632 \\u0628\\u0627 \\u0627\\u0633\\u062a\\u0627\\u062f\\u06a9\\u062a\",\"image\":\"1500801181_ostadcat_slider_1.jpg\",\"status\":1,\"created_at\":\"2017-07-23 04:43:01\",\"updated_at\":\"2017-07-23 04:43:01\"},{\"id\":6,\"title\":\"\\u06cc\\u06a9\\u06cc \\u0628\\u0631\\u0627\\u06cc \\u0647\\u0645\\u0647, \\u0647\\u0645\\u0647 \\u0628\\u0631\\u0627\\u06cc \\u06cc\\u06a9\\u06cc\",\"image\":\"1500801699_ostadcat_slider_3.jpg\",\"status\":1,\"created_at\":\"2017-07-23 04:51:39\",\"updated_at\":\"2017-07-23 04:51:39\"},{\"id\":7,\"title\":\"\\u062d\\u0631\\u0641\\u0647 \\u0627\\u06cc \\u062a\\u0631\\u06cc\\u0646 \\u0627\\u067e\\u0644\\u06cc\\u06a9\\u06cc\\u0634\\u0646 \\u0645\\u0648\\u0633\\u06cc\\u0642\\u06cc\",\"image\":\"1500801728_ostadcat_slider_4.jpg\",\"status\":1,\"created_at\":\"2017-07-23 04:52:08\",\"updated_at\":\"2017-07-23 04:52:08\"},{\"id\":8,\"title\":\"\\u062a\\u0648 \\u0647\\u0645 \\u0645\\u06cc \\u062a\\u0648\\u0646\\u06cc \\u0645\\u062b\\u0644 \\u0645\\u0646 \\u0628\\u0627\\u0634\\u06cc!!!\",\"image\":\"1500801751_ostadcat_slider_2.jpg\",\"status\":1,\"created_at\":\"2017-07-23 04:52:31\",\"updated_at\":\"2017-07-23 04:52:31\"}],\"tutorials\":[{\"id\":1,\"home_image\":\"1500806287_img_home_test_6.png\",\"tutorial_image\":\"1500809220_Hot-Romanian-Inna-in-black-goggles-wallpapers.jpg\",\"tutorial_title\":\"\\u062e\\u0648\\u0627\\u0646\\u0646\\u062f\\u06af\\u06cc\",\"tutorial_description\":\"\\u0622\\u0645\\u0648\\u0632\\u0634 \\u062c\\u0627\\u0645\\u0639 \\u062e\\u0648\\u0627\\u0646\\u0646\\u062f\\u06af\\u06cc\",\"video\":\"1500810916_innaHot2.mp4\",\"video_title\":\"\\u062e\\u0648\\u0627\\u0646\\u0646\\u062f\\u06af\\u06cc \\u0631\\u0627 \\u062d\\u0631\\u0641\\u0647 \\u0627\\u06cc \\u06cc\\u0627\\u062f \\u0628\\u06af\\u06cc\\u0631\\u06cc\\u062f\",\"teacher_image\":\"1500808975_inna-dark-hair-white-dresses-digital-art.jpg\",\"teacher_name\":\"\\u0627\\u06cc\\u0646\\u0627\",\"teacher_bio\":\"\\u0628\\u0647\\u062a\\u0631\\u06cc\\u0646 \\u0627\\u0632 \\u0633\\u0627\\u0644 2009 \\u062a\\u0627 \\u0628\\u0647 \\u0627\\u0644\\u0627\\u0646\",\"status\":1,\"created_at\":\"2017-06-29 17:31:20\",\"updated_at\":\"2017-07-23 11:55:16\"},{\"id\":2,\"home_image\":\"1500802877_img_home_test_1.jpg\",\"tutorial_image\":\"1500802877_Image.png\",\"tutorial_title\":\"\\u0622\\u0645\\u0648\\u0632\\u0634 \\u06af\\u06cc\\u062a\\u0627\\u0631 \\u0627\\u0633\\u0644\\u0634\",\"tutorial_description\":\"\\u06af\\u06cc\\u062a\\u0627\\u0631 \\u0627\\u0633\\u0644\\u0634 \\u0631\\u0627 \\u06cc\\u0627\\u062f \\u0628\\u06af\\u06cc\\u0631\\u06cc\\u062f!!!\",\"video\":\"1500804433_oneRepublic.mp4\",\"video_title\":\"\\u0646\\u0645\\u0648\\u0646\\u0647 \\u0622\\u0645\\u0648\\u0632\\u0634 \\u06af\\u06cc\\u062a\\u0627\\u0631\",\"teacher_image\":\"1500802882_maxresdefault.jpg\",\"teacher_name\":\"\\u0648\\u0627\\u0646 \\u0631\\u06cc\\u067e\\u0627\\u0628\\u0644\\u06cc\\u06a9\",\"teacher_bio\":\"\\u06af\\u0631\\u0648\\u0647 \\u0648\\u0627\\u0646 \\u0631\\u06cc\\u067e\\u0627\\u0628\\u0644\\u06cc\\u06a9 \\u0634\\u0627\\u0645\\u0644 5 \\u0639\\u0636\\u0648\",\"status\":1,\"created_at\":\"2017-06-29 17:35:09\",\"updated_at\":\"2017-07-23 05:37:13\"}]}")

使用此功能后:

RestApiManager.sharedInstance.getFirstPageApplication(EMPTY:"-") {
        response in
        let sliders = JSON(response["sliders"])

        print("response: \(response)")
  }

我的回答与json格式不同:

response: {
    sliders =     (
                {
            "created_at" = "2017-07-23 04:43:01";
            id = 4;
            image = "1500801181_ostadcat_slider_1.jpg";
            status = 1;
            title = "\U0647\U0645\U06cc\U0634\U0647 \U0628\U0647 \U0622\U0648\U0627\U0632 \U0628\U0627 \U0627\U0633\U062a\U0627\U062f\U06a9\U062a";
            "updated_at" = "2017-07-23 04:43:01";
        },
                {
            "created_at" = "2017-07-23 04:51:39";
            id = 6;
            image = "1500801699_ostadcat_slider_3.jpg";
            status = 1;
            title = "\U06cc\U06a9\U06cc \U0628\U0631\U0627\U06cc \U0647\U0645\U0647, \U0647\U0645\U0647 \U0628\U0631\U0627\U06cc \U06cc\U06a9\U06cc";
            "updated_at" = "2017-07-23 04:51:39";
        },
                {
            "created_at" = "2017-07-23 04:52:08";
            id = 7;
            image = "1500801728_ostadcat_slider_4.jpg";
            status = 1;
            title = "\U062d\U0631\U0641\U0647 \U0627\U06cc \U062a\U0631\U06cc\U0646 \U0627\U067e\U0644\U06cc\U06a9\U06cc\U0634\U0646 \U0645\U0648\U0633\U06cc\U0642\U06cc";
            "updated_at" = "2017-07-23 04:52:08";
        },
                {
            "created_at" = "2017-07-23 04:52:31";
            id = 8;
            image = "1500801751_ostadcat_slider_2.jpg";
            status = 1;
            title = "\U062a\U0648 \U0647\U0645 \U0645\U06cc \U062a\U0648\U0646\U06cc \U0645\U062b\U0644 \U0645\U0646 \U0628\U0627\U0634\U06cc!!!";
            "updated_at" = "2017-07-23 04:52:31";
        }
    );
    tutorials =     (
                {
            "created_at" = "2017-06-29 17:31:20";
            "home_image" = "1500806287_img_home_test_6.png";
            id = 1;
            status = 1;
            "teacher_bio" = "\U0628\U0647\U062a\U0631\U06cc\U0646 \U0627\U0632 \U0633\U0627\U0644 2009 \U062a\U0627 \U0628\U0647 \U0627\U0644\U0627\U0646";
            "teacher_image" = "1500808975_inna-dark-hair-white-dresses-digital-art.jpg";
            "teacher_name" = "\U0627\U06cc\U0646\U0627";
            "tutorial_description" = "\U0622\U0645\U0648\U0632\U0634 \U062c\U0627\U0645\U0639 \U062e\U0648\U0627\U0646\U0646\U062f\U06af\U06cc";
            "tutorial_image" = "1500809220_Hot-Romanian-Inna-in-black-goggles-wallpapers.jpg";
            "tutorial_title" = "\U062e\U0648\U0627\U0646\U0646\U062f\U06af\U06cc";
            "updated_at" = "2017-07-23 11:55:16";
            video = "1500810916_innaHot2.mp4";
            "video_title" = "\U062e\U0648\U0627\U0646\U0646\U062f\U06af\U06cc \U0631\U0627 \U062d\U0631\U0641\U0647 \U0627\U06cc \U06cc\U0627\U062f \U0628\U06af\U06cc\U0631\U06cc\U062f";
        },
                {
            "created_at" = "2017-06-29 17:35:09";
            "home_image" = "1500802877_img_home_test_1.jpg";
            id = 2;
            status = 1;
            "teacher_bio" = "\U06af\U0631\U0648\U0647 \U0648\U0627\U0646 \U0631\U06cc\U067e\U0627\U0628\U0644\U06cc\U06a9 \U0634\U0627\U0645\U0644 5 \U0639\U0636\U0648";
            "teacher_image" = "1500802882_maxresdefault.jpg";
            "teacher_name" = "\U0648\U0627\U0646 \U0631\U06cc\U067e\U0627\U0628\U0644\U06cc\U06a9";
            "tutorial_description" = "\U06af\U06cc\U062a\U0627\U0631 \U0627\U0633\U0644\U0634 \U0631\U0627 \U06cc\U0627\U062f \U0628\U06af\U06cc\U0631\U06cc\U062f!!!";
            "tutorial_image" = "1500802877_Image.png";
            "tutorial_title" = "\U0622\U0645\U0648\U0632\U0634 \U06af\U06cc\U062a\U0627\U0631 \U0627\U0633\U0644\U0634";
            "updated_at" = "2017-07-23 05:37:13";
            video = "1500804433_oneRepublic.mp4";
            "video_title" = "\U0646\U0645\U0648\U0646\U0647 \U0622\U0645\U0648\U0632\U0634 \U06af\U06cc\U062a\U0627\U0631";
        }
    );
}

我在这里遇到了例外:

func initialFirstView()
    {
        RestApiManager.sharedInstance.getFirstPageApplication(EMPTY:"-"){
            response in
            let sliders = JSON(response["sliders"])

            print("response: \(response)")

            for item in (sliders.array)! // the error is in this line 
            {

                var slider = Slider.init(mid: String(describing: item["id"]), mtitle: String(describing: item["title"]), mimage: String(describing: item["image"]), mstatus: String(describing: item["status"]), mcreated_at: String(describing: item["created_at"]), mupdated_at: String(describing: item["updated_at"]))

                self.sliders.append(slider)

            }

            self.showSliders()

        }
    }

我在这里有错误:    对于(sliders.array)中的项目!

此行的输出:print("response: \(sliders)")

  

回复:未知

1 个答案:

答案 0 :(得分:4)

我没有,因为我收到的JSON不是UTF8格式。

没有,你错了。 np.random.poisson只能使用UTF-8编码数据。并且JSONSerialization将有效的UTF-8编码的JSON数据转换为Swift(和Objective-C)可以处理的对象。

如何将UTF8用于此功能:JSONSerialization.jsonObject?

正如我上面所写,JSONSerialization.jsonObject(with:options:)使用UTF-8。

我的回复与json格式不同:

JSONSerialization.jsonObject(with:options:)将输入的JSON数据转换为Objective-C对象,如下所示:

JSONSerialization.jsonObject(with:options:)

您看到的是来自JSON object -> NSDictionary JSON array -> NSArray JSON number -> NSNumber JSON string -> NSString JSON true -> NSNumber JSON false -> NSNumber JSON null -> NSNull NSDictionary的输出,NSArray已成功完成转化。

我在这里有错误:对于(sliders.array)中的项目!

此行的输出:JSONSerialization.jsonObject(with:options:)

  

回复:未知

然后上一行:print("response: \(sliders)")未按预期工作。可能是let sliders = JSON(response["sliders"])的错误。

您没有指定正在使用的库,但您无需使用此类库:

试试这个:

JSON.init(_:)

我不确定这可能导致 print("response: \(response)") guard let response = response as? [String: Any] else { fatalError("response is not a JSON object") } guard let sliders = response["sliders"] as? [[String: Any]] else { fatalError("sliders is not a JSON array") } for item in sliders { let slider = Slider(mid: String(item["id"] as? Int ?? 0), mtitle: item["title"] as? String ?? "", mimage: item["image"] as? String ?? "", mstatus: String(item["status"] as? Int ?? 0), mcreated_at: item["created_at"] as? String ?? "", mupdated_at: item["updated_at"] as? String ?? "") self.sliders.append(slider) } self.showSliders() 的意外行为,但是在这行代码中:

JSON.init(_:)

您无需指定选项let jsonResult = try JSONSerialization.jsonObject(with: usableData, options: JSONSerialization.ReadingOptions.mutableContainers) 。它可以简化为:

JSONSerialization.ReadingOptions.mutableContainers