本文介绍了在Swift中制作一个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将JSON数据从我的iOS应用发送到服务器.我在此链接中找到了一个教程. "obj:AnyObject"应如何显示,以便可以调用此方法:
I'm trying to send JSON data to a server from my iOS app. I found a tutorial on this link. How should the "obj: AnyObject" look like so that this method can be called:
NSJSONSerialization.dataWithJSONObject(obj: AnyObject, options: NSJSONWritingOptions, error: NSErrorPointer)它不接受字典(即使在上面的链接中的示例中以某种方式使用了字典)或数组.
It doesn't accept Dictionary (even though it is somehow used in the example on the link above) or Array.
推荐答案假设您拥有
let dictionary = ["key1": "value1", "key2": "value2"]要使用您提供的方法生成JSON数据,只需调用它即可:
To generate your JSON Data using the method you provided you just call it:
var jsonGenerationError: NSError? let jsonData = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted, error: &jsonGenerationError)您可以通过解析生成的数据来验证它是否有效:
You can verify it worked by parsing the generated data:
var jsonParsingError: NSError? let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments, error:&jsonParsingError)雨燕4
let dictionary = ["key1": "value1", "key2": "value2"] let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) // Verifying it worked: let parsedObject = try! JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)更多推荐
在Swift中制作一个JSON对象
发布评论