在Swift中制作一个JSON对象 [英] Making a JSON object in Swift

查看:92
本文介绍了在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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆