将Objective-C对象序列化和反序列化为JSON [英] Serialize and Deserialize Objective-C objects into JSON
问题描述
我需要将Objective-C对象序列化和反序列化为JSON以存储在CouchDB中.人们是否有通用解决方案最佳实践的示例代码?我看了几个JSON框架,它们在NSDictionary/NSArray级别停止了.即,许多框架会将NSDictionary/NSArray序列化和反序列化为JSON.但是我仍然要做将NSDictionary转换为Objective-C对象的工作.
I need to serialize and deserialize objective-c objects into JSON to store in CouchDB. Do people have any example code for best practice for a general solution? I looked at a few JSON framework and they are stopped at the NSDictionary/NSArray level. i.e. A lot of framework will serialize and deserialize NSDictionary/NSArray into JSON. But I still have to do the work to convert NSDictionary into Objective-C objects.
为了使事情更复杂,我的对象A可以引用对象B的NSArray/NSDictionary.
To make things more complex, my Object A can have reference to an NSArray/NSDictionary of Object Bs.
除了收集要求外,我的问题与该问题非常相似.
My question is very similar to this question with addition of the collection requirement.
推荐答案
听起来您正在寻找一个序列化库,该库可以让您将自己的自定义类的对象转换为JSON,然后将其重新构造.属性列表类型(NSArray,NSNumber等)的序列化已存在于第三方库中,甚至内置于OS X 10.7和iOS 5中.
It sounds like you're looking for a serialization library that can let you convert objects of your own custom classes into JSON, and then reconstitute them back. Serialization of property-list types (NSArray, NSNumber, etc.) already exists in 3rd party libraries, and is even built into OS X 10.7 and iOS 5.
所以,我认为答案基本上是否".我在一两个月前在cocoa-dev邮件列表上问了这个确切的问题,最接近我的是迈克·阿卜杜拉(Mike Abdullah),他指向他写的一个实验库:
So, I think the answer is basically "no". I asked this exact question a month or two ago on the cocoa-dev mailing list, and the closest I got to a hit was from Mike Abdullah, pointing to an experimental library he'd written:
https://github.com/mikeabdullah/KSPropertyListEncoder
这会将对象存档到内存中的属性列表,但是正如我所说的,已经有将这些对象转换为JSON的API.
This archives objects to in-memory property lists, but as I said there are already APIs for converting those into JSON.
还有一个名为Objectify的商业应用程序,它声称能够执行类似的操作:
There's also a commercial app called Objectify that claims to be able to do something similar:
http://tigerbears.com/objectify/
作为我的CouchCocoa库的一部分,我最终可能会实现您的要求,但我尚未深入研究该任务.
It's possible I'll end up implementing what you're asking for as part of my CouchCocoa library, but I haven't dived into that task yet.
https://github.com/couchbaselabs/CouchCocoa
这篇关于将Objective-C对象序列化和反序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!