简体   繁体   English

将自定义对象序列化为NSDictionary或NSArray以使用NSJSONSerialization

[英]Serializing a custom object into NSDictionary or NSArray to use NSJSONSerialization

I've been looking for a way to serialize custom objects with NSJSONSerialization avoiding the use of third-party libraries, and I couldn't find any example. 我一直在寻找一种使用NSJSONSerialization序列化自定义对象的方法, NSJSONSerialization避免了使用第三方库,而且我找不到任何示例。 Is there any way of "automatically" create an NSDictionary and NSArray from an object, without having to create it typing in code all the object's member names yourself one by one and setting manually the values? 有什么方法可以从对象“自动”创建NSDictionaryNSArray ,而不必通过键入代码来创建对象,所有对象的成员自己一个个地命名自己并手动设置值吗? I found a related post , but it is pretty old, things may have now changed. 我找到了相关的文章 ,但是它已经很旧了,现在情况可能已经改变了。

Thanks 谢谢

You can use KVC to ask any object for dictionaryWithValuesForKeys: which will give you a dictionary representation of the object. 您可以使用KVC向任何对象询问dictionaryWithValuesForKeys: :,这将为您提供该对象的字典表示。

If you need to change the property / key names then you want to do some mapping and (depending on what you're using the JSON for) you may find RestKit useful. 如果您需要更改属性/键名,则需要进行一些映射,并且(取决于您使用JSON的方式),您可能会发现RestKit有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM