将JSON转换为字典数组的Swift会发出错误代码3840(末尾为垃圾)



在HTML请求中,我从数据库下载了一个JSON文件。这是我得到的JSON文件。

{"_id":{"$oid":"5e8e09d0bf75d176ecfa2101"},"name":"Pasta al pomodoro","category":"Primi","ingredients":"","price":"15.99","available":true}{"_id":{"$oid":"5e8e0c2da73abb76ec812daf"},"name":"Cotoletta","category":"Carne","ingredients":"Cotoletta, Limone","price":"25.99","available":true}

我尝试将JSON文件转换为字典数组,这样我就可以通过以下操作来选择项目:

myArray[0]['name']

这是我用来尝试转换JSON:的代码

do {
let myArray = try (JSONSerialization.jsonObject(with: data, options : .mutableContainers) as? [Dictionary<String, Any>])!
print(myArray)
//completion(myArray, nil)
}

但它似乎不起作用;它返回错误消息:

错误域=NSCocoaErrorDomain代码=3840"结束时的垃圾。"UserInfo={NSDebugDescription=结束时的废物。}

问题出在PHP服务器上,因为它没有正确发出JSON文件。为了修复它,我必须确保PHP文件在第一个DB行之前回显一个"[",在每个DB行之间包括一个",",并以"]"结束文件。

之前:

foreach ($rows as $document) {
echo(json_encode($document));
}

之后:

echo "[";
foreach ($rows as $document) {
echo(json_encode($document));
echo (", ");
}
echo "]";

相关内容

最新更新