【问题标题】:Swift converting JSON to dictionary array issues Error Code 3840 (Garbage at end)Swift 将 JSON 转换为字典数组问题 错误代码 3840(末尾有垃圾)
【发布时间】:2020-07-21 06:52:31
【问题描述】:

在整个 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=垃圾结束。}

【问题讨论】:

  • 尝试从你的 jsonSerilization 中移除 options 参数]
  • 已经试过了,没用。
  • 您不能将字典转换为带有JSONSerialization 的数组,并且 JSON 似乎是字典。无论如何,.mutableContainers 在 Swift 中毫无意义。
  • 那么你将如何解决这个问题?
  • 您的 JSON 有问题,将您的响应输入到格式化程序会出现错误。 jsonformatter.curiousconcept.com

标签: json swift jsonserializer


【解决方案1】:

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

之前:

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

之后:

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

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2019-11-29
    • 2016-06-11
    • 2016-07-10
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多