Swift - 字符 0 周围的值无效



我知道这已经得到了回答,但是这个错误的答案还没有帮助。

我正在尝试从服务器获取数据并将其放在表视图中,但它不会显示。我有这段代码来确定是否接收数据:

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error != nil {
            print("Failed to download data")
        }else {
            print("Data downloaded")
            self.parseJSON()
        }
    }

但它不起作用。控制台的输出为:

 Data downloaded
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

那么为什么数据说它已下载,但后来我收到错误?我的网址绝对正确。

这是我的解析JSON函数:

func parseJSON() {
    var jsonResult: NSMutableArray = NSMutableArray()
    do{
        jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
    } catch let error as NSError {
        print(error)
    }
    var jsonElement: NSDictionary = NSDictionary()
    let locations: NSMutableArray = NSMutableArray()
    for(var i = 0; i < jsonResult.count; i++)
    {
        jsonElement = jsonResult[i] as! NSDictionary
        let location = LocationModel()
        //the following insures none of the JsonElement values are nil through optional binding
        if let accented = jsonElement["Accented"] as? String,
            let unaccented = jsonElement["Unaccented"] as? String
        {
            location.accented = accented
            location.unaccented = unaccented
        }
        locations.addObject(location)
    }
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.delegate.itemsDownloaded(locations)
    })
}

以下是来自服务器的数据:

<html>n<head>n<meta http-equiv="content-type" content="text/html; charset=utf-8">n</head>n<body>n[{"id":"1","accented":"mē","unaccented":"me"},{"id":"2","accented":"quid","unaccented":"quid"},{"id":"3","accented":"nihil","unaccented":"nihil"},{"id":"4","accented":"nōn","unaccented":"non"},{"id":"5","accented":"saepe","unaccented":"saepe"},{"id":"6","accented":"sī","unaccented":"si"},{"id":"7","accented":"amō, amāre, amāvī, amātum","unaccented":"amo"},{"id":"8","accented":"amābō tē","unaccented":"amabo te"},{"id":"9","accented":"cōgitō, cōgitāre, cōgitāvī, cōgitātum","unaccented":"cogito"},{"id":"10","accented":"dēbeō, dēbēre, dēbuī, dēbitum","unaccented":"debeo"},{"id":"11","accented":"dō, dare, dedī, datum","unaccented":"do"},{"id":"12","accented":"errō, errāre, errāvī, errātum","unaccented":"erro"},{"id":"13","accented":"laudō, laudāre, laudāvī, laudātum","unaccented":"laudo"},{"id":"14","accented":"moneō, monēre, monuī, monitum","unaccented":"moneo"},{"id":"15","accented":"salveō, salvēre","unaccented":"salveo"},{"id":"16","accented":"salvē, salvēte","unaccented":"salve"},{"id":"17","accented":"servō, servāre, servāvī, servātum","unaccented":"servo"},{"id":"18","accented":"cōnservō, cōnservāre, cōnservāvī, cōnservātum","unaccented":"conservo"},{"id":"19","accented":"terreō, terrēre, terruī, territum","unaccented":"terreo"},{"id":"20","accented":"valeō, valēre, valuī, valitūrum","unaccented":"valeo"},{"id":"21","accented":"valē, valēte","unaccented":"vale"},{"id":"22","accented":"videō, vidēre, vīdī, vīsum","unaccented":"video"},{"id":"23","accented":"vocō, vocāre, vocāvī, vocātum","unaccented":"voco"}]</body>n</html>

问题是来自服务器的响应不是 JSON。这是一个 HTML 响应,其<BODY>是 JSON。您必须从响应正文中删除这些 HTML 标记。


在聊天中,我们发现您的 PHP 目前显示:

<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
</head> 
<body> 
<?php 
require 'database_data.php'; 
$dbc = mysqli_connect($site, $username, $password,$db) OR die('ERROR! Could not connect to the database.'); 
mysqli_set_charset($dbc, 'utf8'); 
$query = 'SELECT * FROM database'; 
if ($result = mysqli_query($dbc, $query)) 
{ 
    // If so, then create a results array and a temporary one 
    // to hold the data 
    $resultArray = array(); 
    $tempArray = array(); 
    // Loop through each row in the result set 
    while($row = $result->fetch_object()) 
    { 
        // Add each row into our results array 
        $tempArray = $row; 
        array_push($resultArray, $tempArray); 
    } 
    // Finally, encode the array to JSON and output the results 
    echo json_encode($resultArray, JSON_UNESCAPED_UNICODE); 
} 
?> 
</body> 
</html>

您应该从文件中删除 HTML 标记。它应该只是:

<?php 
require 'database_data.php'; 
$dbc = mysqli_connect($site, $username, $password,$db) OR die('ERROR! Could not connect to the database.'); 
mysqli_set_charset($dbc, 'utf8'); 
$query = 'SELECT * FROM database'; 
if ($result = mysqli_query($dbc, $query)) 
{ 
    // If so, then create a results array and a temporary one 
    // to hold the data 
    $resultArray = array(); 
    $tempArray = array(); 
    // Loop through each row in the result set 
    while($row = $result->fetch_object()) 
    { 
        // Add each row into our results array 
        $tempArray = $row; 
        array_push($resultArray, $tempArray); 
    } 
    mysqli_close($dbc); 
    // Finally, encode the array to JSON and output the results 
    header("Content-Type", "application/json");
    echo json_encode($resultArray, JSON_UNESCAPED_UNICODE); 
} 
?> 

另请注意,我添加了Content-Type标头,以便响应正确格式化为 JSON。

就个人而言,我倾向于将失败更改为也输出 JSON,而不仅仅是调用die(以便应用程序可以优雅地检测错误),但这并不那么重要。

最新更新