在 swift 3 中打印 json 时出现任何下标成员错误 [重复]
Posted
技术标签:
【中文标题】在 swift 3 中打印 json 时出现任何下标成员错误 [重复]【英文标题】:I am getting error of any subscript member error while printing json in swift 3 [duplicate] 【发布时间】:2018-02-19 07:29:21 【问题描述】:我不知道该怎么做,请帮助我 错误是:
类型 'Any' 没有下标成员
import UIKit
class ViewController: UIViewController
@IBOutlet weak var Lab: UILabel!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let url = URL(string: "MY URL")
processData(url: url);
private func processData(url: URL)
let task = URLSession.shared.dataTask(with: url) (data, response, error) -> Void in
if error != nil
print(error)
else
if let result = data
do
let json = try JSONSerialization.jsonObject(with: result, options:JSONSerialization.ReadingOptions.mutableContainers)
print(json)
if let name = json["bname"] as? String
print (name);
catch let error as NSError
print("error is \(error)")
task.resume()
我的 JSON 是:
"bank_detail" = (
0 = 1;
1 = www;
2 = "PRAKHAR SONI";
3 =123;
4 = UDAIPUR;
5 = ee;
6 = 3190;
7 = "2017-03-15";
8 = "2017-03-15 13:31:39";
accno = 123;
bid = 1;
bname = www;
"branch_code" = 3190;
"branch_name" = UDAIPUR;
date = "2017-03-15";
"date_time" = "2017-03-15 13:31:39";
ifsc = www;
uname = "PRAKHAR SONI";
,
0 = 3;
1 = "www ";
2 = "Sureshkumar Soni";
3 = "123 ";
4 = "UDAIPUR ";
5 = "www ";
6 = "3190 ";
7 = "2017-03-17";
8 = "2017-03-17 12:24:24";
accno = "www ";
bid = 3;
bname = "www ";
"branch_code" = "3190 ";
"branch_name" = "UDAIPUR ";
date = "2017-03-17";
"date_time" = "2017-03-17 12:24:24";
ifsc = "www ";
uname = "Sureshkumar Soni";
);
【问题讨论】:
这很正常。你从来没有说过json
可以有下标(意思是你可以做json["someKey"]
)。默认情况下,它是一个 Any
对象。所以告诉编译器这是一个[String:Any]
和let json = try JSONSerialization.jsonObject(with: result, options:[]) as? [String: Any]
。你也不应该在 Swift 中需要 mutableContainers
。
顺便说一句,既然您已经展示了 JSON,json["bname"]
将返回 nil,因为您不了解 JSON 的结构。
【参考方案1】:
您的问题是没有将 json 转换为预期的内容,例如 [String:Any] 如果它是字典,或者 [String] 是字符串数组,您可以试试这个
let json = try JSONSerialization.jsonObject(with: result, options:JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]
【讨论】:
以上是关于在 swift 3 中打印 json 时出现任何下标成员错误 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
将文本从 UITextView 保存到领域(Swift 5)时出现问题
在 tableview 上的对象中打印 json 数组时出现问题
Swift 解析 JSON 时出现问题:无法将“__NSCFDictionary”类型的值转换为“NSArray”错误