简体   繁体   English

在Swift 4中从PHP解析JSON

[英]Parsing JSON from PHP in Swift 4

I'm getting an error when loading JSON from a PHP output page using Swift 4. 使用Swift 4从PHP输出页面加载JSON时出现错误。

Note: The PHP script has been checked and is working fine 注意:已检查PHP脚本,并且可以正常工作

let myUrl = URL(string: "http://localhost/swift/signin_up/login.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
DispatchQueue.main.async {
    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            print("error=\(error!)")
            return
        }

        // You can print out response object
        print("response = \(response!)")
        print("==================================")
        //Let's convert response sent from a server side script to a NSDictionary object:
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                print(parseJSON)
            }
        } catch {
            print(" error:\(error)")
        }
    }
    task.resume()

I get this error message from Xcode: 我从Xcode收到此错误消息:

error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." 错误:错误域= NSCocoaErrorDomain代码= 3840“ JSON文本不是以数组或对象开头,并且没有允许设置片段的选项。” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且没有允许设置片段的选项。}

When I changed options to: 当我将选项更改为:

options: [.mutableContainers, .allowFragments]

I get this error message: 我收到此错误消息:

error: Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." 错误:错误域= NSCocoaErrorDomain代码= 3840“垃圾在结尾。” UserInfo={NSDebugDescription=Garbage at end.} UserInfo = {NSDebugDescription =垃圾末。}

This is the PHP output I tested: 这是我测试的PHP输出:

{"id":"1","email":"aa","password":"aa"}

Be careful when you set character_set in database server choose (utf8_unicode_ci) to get correct json format when using 在数据库服务器中设置character_set时请谨慎选择(utf8_unicode_ci)以在使用时获取正确的json格式

json_encode(//json variable);

in php 在PHP中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM