将 NSDictionary 对象转换为自定义复杂对象
我需要将 JSON 字符串反序列化为自定义复杂对象。
例如,假设我有 json 字符串:
{"Menu": {
"categoryList": {
"Category": [
{"name": "Cat1"},
{"name": "Cat1"},
{"name": "Cat3"}
]
}
}}
如何反序列化该字符串以初始化具有 CategoryList 的 Menu 对象,其中包含 3 个 Category 类类型的类别对象?有什么办法吗?
I need to deserialize JSON string to custom complex objects.
For example lets say I have the json string:
{"Menu": {
"categoryList": {
"Category": [
{"name": "Cat1"},
{"name": "Cat1"},
{"name": "Cat3"}
]
}
}}
How can I deserialize this string to initialize a Menu object that has a categoryList which includes 3 category objects of type Category class? Is there any way to to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一项必需的功能,但似乎不存在良好的(公共)解决方案。
This is a needed capability for which there does not seem to exist a good (public) solution.
尝试使用 JSON 解析器。
http://code.google.com/p/json-framework/
它将分析你的字符串并返回一个代表你的数据的 NSObject (NSArray 或 NSDictionary)。
编辑:
嗯,由于OP想要获得一个自定义对象而不是NSDictionary/NSArray,它可以实现如下(假设困难将获得正确的数据并设置每个新的对象属性)
基于代码提供者@andrewsardone,在使用更适合您的项目的任何解决方案处理 JSON 解析之后,可以使用 KVO 轻松实现一个函数来获取具有相应属性设置的新对象
Try using a JSON parser.
http://code.google.com/p/json-framework/
It will analyse your string and give you back an NSObject (NSArray or NSDictionary) that represents your data.
EDIT:
Well, as the OP wanted to get a custom object instead of an NSDictionary/NSArray, it could be implemented something as the following (assuming that the dificulty would get the correct data and set each of the new object properties)
Based on the code provided by @andrewsardone, one could easily implement a function using KVO to get a new object with the properties set accordingly, after handling the JSON parsing with whatever solution fits your project better