当我将NSString转换为JSON时,我得到null

时间:2016-11-02 00:48:47

标签: ios json swift nsstring

我正在做一些webscrapping,并且能够从我想要的页面获取html源代码,但我将它转换为NSString。当我尝试将其转换为JSON时,当我尝试打印它时,我得到一个null。当我打印responseString2时,我看到的是源代码,但是作为NSString。我做错了什么?

let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) { data2, response, error in
            guard error == nil && data2 != nil else {                                                          // check for fundamental networking error
                print("error2=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode2 should be 200, but is \(httpStatus.statusCode)")
                print("response2 = \(response)")
            }

            let responseString2 = NSString(data: data2!, encoding: String.Encoding.utf8.rawValue)

            print("hthpage \(responseString2)")
            if let dataFromString = responseString2?.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false){
                let json = JSON(data: dataFromString)
                print("JASON \(json)")
            }

1 个答案:

答案 0 :(得分:0)

不要转换数据 - >字符串 - >数据。

试试此代码

并在将数据转换为json时发生错误时检查错误。

    URLSession.shared.dataTask(with: request!) { (d, response, error) in

        if let data = d
        {
            if let str = String(data: data, encoding: String.Encoding.utf8)
            {
                print("data->string : " + str)
            }

            do
            {
                if let obj = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
                {
                    DispatchQueue.main.async {
                        complete(obj)
                    }
                }
                else
                {
                    print("Http - JsonSerialization Failed, not String:AnyObject Type!!")
                }
            }
            catch let err as NSError
            {
                print("Http - JsonSerialization Error")
                print(err)
            }
        }
        else
        {
            if error != nil
            {
                print("Http - URLSession.shared.dataTask Error")
                print(error)
            }
        }
        }.resume()