Swift - 字符0周围的值无效

时间:2016-05-23 00:02:13

标签: ios json swift

我知道这已经得到了解答,但是这里针对此错误的答案还没有帮助。

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

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.}

那么为什么数据说下载了然后我收到了错误?我的网址肯定是正确的。

这是我的parseJSON函数:

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>

2 个答案:

答案 0 :(得分:1)

问题是来自服务器的响应不是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(以便应用程序可以优雅地检测错误),但这不那么重要。

答案 1 :(得分:0)

  

那么为什么数据说它已经下载但我得到了一个错误

因为可以成功下载数据但是无法将该数据解析为JSON。这是两个完全不同的操作。