在Swift中制作一个JSON对象

编程入门 行业动态 更新时间:2024-10-09 16:24:52
本文介绍了在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对象

本文发布于:2023-11-26 09:02:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Swift   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!