我正在尝试从网站获取 JSON 并在打印之前对其进行解析。 我有一个名为“JSONImport”的类,它应该处理来自服务器的 JSON 导入并打印它。 第二个类应该调用以启动导入并打印 JSON 的内容。
下面的代码是我到目前为止所拥有的(我从另一个问题 Downloading and parsing json in swift 中获取它)
这是我的“JSONImport.swift”:
var data = NSMutableData();
func startConnection(){
let urlPath: String = "http://echo.jsontest.com/key/value";
let url: NSURL = NSURL(string: urlPath)!;
let request: NSURLRequest = NSURLRequest(URL: url);
let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!;
connection.start();
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data);
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// throwing an error on the line below (can't figure out where the error message is)
do{
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
print(jsonResult);}
catch {
print("Something went wrong?");
}
}
在另一个类中,我想通过以下方式打印 JSON:
JSONImport.startConnection();
现在我收到一个错误,因为 swift 希望我向调用添加一个参数,使其看起来像:
JSONImport.startConnection(<#T##JSONImport#>);
有人知道我应该把什么作为参数放在那里吗? 我很困惑,因为我没有声明。
先谢谢大家了!
亲切的问候,曼努埃尔
最佳答案
startConnection()
是一个实例方法,因此您需要实例化一个 JSONImport
来调用它。
只有类型方法可以这样使用。所以它本质上是在请求一个 JSONImport
实例。
这是你应该如何做
let importer = JSONImport()
importer.startConnection()
或者通过从类型方法调用
let importer = JSONImport()
JSONImport.startConnection(importer)
您可以在 guide 阅读有关实例/类型方法的更多信息。
关于json - 下载/解析后在 swift 中打印 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35228615/