I'm relatively new to iOS programming. However, I would have assumed that Swift would have an automated way of converting objects to JSON and vice versa. That being said, I have found several libraries that can do this.

然而

看起来,无论您如何将数据发布到web服务(甚至使用AlamoFire之类的工具),请求都必须是字典.所有这些论坛都展示了如何轻松地将返回的JSON字符串转换为对象.符合事实的但请求需要手动编码.也就是说,遍历所有对象属性并将它们映射为字典.

所以我的问题是:我错过了什么吗?我是否完全弄错了,有一种超级简单的方法可以(a)在请求中发送JSON(而不是字典),或者(b)自动将对象转换为字典?

Again, I see how easy it is to deal with a JSON response. I'm just looking for an automatic way to convert the request object I want to post to a web service into a format that a library like AlamoFire (or whatever) requires. With other languages this is fairly trivial, so I'm hoping there's an equally easy and automated way with Swift.

推荐答案

Swift currently does not support advanced reflection like Java or C# so the answer is: no, there is not an equally easy and automated way with pure Swift.

[更新]同时,SWIFT 4拥有Codable协议,允许串行化JSON和PLIST.

typealias Codable = Decodable & Encodable

Json相关问答推荐

如何在使用GO时检测JSON中不需要的字段?

将嵌套的json中的字符串强制转换为数字

Vega图表计数聚合如果数据值为空数组则不显示任何内容,如何解决此问题?

来自json的可分析的构建报告

使用 jq 如何更改键的值?

Jolt规范:将嵌套数组中的null元素移除

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

将请求中的数据推送到数组中

jq:来自嵌套 JSON 的映射

如何删除 django jsonfield 中的特定项目

将嵌套的 JSON 对象规范化为 Pandas 数据框

如何找出实际安装了哪个版本的 bower 包?

如何使用 Kotlin + Jackson 将 JSON 反序列化为 List

如何从 mysql 数据库构建 JSON 数组

使用 c# 通用地展平 Json

使用 JSON 的 javascript 深拷贝

在 JSON.NET 中序列化派生类时的字段顺序

无法将空值放入 JSON 对象

在 .NET 中缩小缩进的 JSON 字符串

log4j 支持 JSON 格式吗?