我正在尝试从网络应用程序读取 JSON 输出。这个输出是:
[{"group_name":"XYZ","adminof":0}]
我有一个看起来像这样的结构:
struct grouplistStruct{
var group_name : String
var adminof : Any
}
我正在使用的代码是:
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let loc = grouplistStruct(group_name: jsonResult["group_name"], adminof: jsonResult["adminof"])
我可以看到 jsonArray 正确读取了值。同样在for循环中,jsonResult也正确读取了值
但是当我尝试将此值分配给 Struct 变量时,它显示错误:
Type 'Any' has no subscript members
为什么会发生这种情况?抱歉,我是 Swift 新手,所以我正在学习所有这些。
最佳答案
由于您的 json 数据是一个包含如下字典的数组:
[{"group_name":"XYZ","adminof":0}]
您收到错误
Type 'Any' has no subscript members
因为您将 json 向下转换为 Any
的数组并 swift Any
(顾名思义)代表任何类型,如 Int
, Double
或Dictionary of type [String: String]
如您所知Int
或Double
不能有像 someInt["subscript"]
这样的下标
因此您需要使用 [[String: Any]]
向下转换为此特定类型。
这表示包含 [String: Any] 类型的字典的数组。这将起作用,因为字典可以有下标成员,例如 someDict["group_name"]
因此您应该使用[[String: Any]]
而不是[Any]
在本声明中try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
关于json - 在 Swift 中读取 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386092/