将Objective-C自定义对象序列化为OSX的JSON? [英] serialize objective-c custom object to JSON for OSX?
问题描述
我对Mac开发非常陌生,在寻找优质资源方面遇到了一些麻烦.我当前的问题是自定义的Objective-C类对象序列化为JSON.
I'm very new to Mac development and I'm having some troubles finding good resources. My current problem is a custom objective-c class object serialization to JSON.
我知道苹果库中有一个内置的序列化器,但是只能与Foundation对象一起使用.
I know that there is a built-in serializer in apple libraries, but that one works only with Foundation objects.
就我而言,我有一个自己的类,如下所示:
In my case I have my own class that looks like this:
@interface SomeClass : NSObject
{
int a;
int b;
NSString *aa;
NSString *bb;
}
@property int a,b;
@property NSString *aa,*bb;
@end
如果有人知道如何将这种类型的结构序列化为JSON,请给我一个提示!任何相关信息都将有所帮助!谢谢!
If anyone knows how to serialize this type of structure to a JSON please give me a hint! Any kind of relevant information would help! Thank you!
推荐答案
如果只想序列化包含整数和字符串的对象,最简单的方法是创建NSJSONSerialization
支持并序列化的数据结构:
If you just want to serialize an object that contains integers and strings, the easiest way is to create a data structure that NSJSONSerialization
supports and serialize that:
static const NSString *kAKey = @"a";
static const NSString *kBKey = @"b";
static const NSString *kAaKey = @"aa";
static const NSString *kBbKey = @"bb";
- (id)JSONObject {
return @{
kAKey: @(self.a),
kBKey: @(self.b),
kAaKey: self.aa,
kBbKey: self.bb
};
}
- (NSData *)JSONData {
return [NSJSONSerialization dataWithJSONObject:[self JSONObject] options:0 error:NULL];
}
这篇关于将Objective-C自定义对象序列化为OSX的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!