问题描述
我对iOS编程比较陌生。但是,我以为Swift会采用一种自动的方式将对象转换为JSON,反之亦然。话虽如此,我发现了几个可以做到这一点的库。
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字符串转换为对象有多么容易的示例。真正。但是该请求需要手动编码。也就是说,遍历所有对象属性并将它们映射为字典。
It seems that no matter how you post data to a web service (even using something like AlamoFire), the requests must be a dictionary. All these forums show examples of how easy it is to convert the returned JSON string to objects. True. But the request needs to be manually coded. That is, go through all of the object properties and map them as a dictionary.
所以我的问题是:我是否缺少某些东西?我是否全部弄错了,并且有一种超级简单的方法要么(a)在REQUEST中发送JSON(而不是字典),要么(b)自动将对象转换为字典?
So my question is this: Am I missing something? Have I got this all wrong and there's a super-easy way to either (a) send JSON (instead of a dictionary) in the REQUEST or (b) convert an object automatically to a dictionary?
同样,我看到处理JSON响应是多么容易。我只是在寻找一种自动方法,将要发布到网络服务中的请求对象转换为AlamoFire(或类似工具)之类的库所需的格式。对于其他语言来说,这是微不足道的,所以我希望Swift也有同样简单和自动化的方法。
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当前Swift不支持Java或C#之类的高级反射,所以答案是:不,使用纯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.
[Update] Swift 4有同时使用 Codable
协议,该协议允许与JSON和PLIST进行串行化。
[Update] Swift 4 has meanwhile the Codable
protocol which allows serializing to/from JSON and PLIST.
typealias Codable = Decodable & Encodable
这篇关于如何将Swift对象转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!