【发布时间】: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