将iOS目标C对象转换为JSON字符串

桑卡

我有一个客观的C类,

@interface message : NSObject {
 NSString *from;
 NSString *date;
 NSString *msg;
}

我有此消息类的实例的NSMutableArray。我想使用iOS 5 SDK中的新JSONSerialization API将NSMutableArray中的所有实例序列化为JSON文件。我怎样才能做到这一点 ?

是否通过遍历NSArray中元素的每个实例来创建每个键的NSDictionary?有人可以提供有关如何解决此问题的代码的帮助吗?我无法在Google中获得良好的结果,因为“ JSON”将结果偏向服务器端调用和数据传输而不是序列化。非常感谢。

编辑:

NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON Output: %@", jsonString);
淑女

编辑:我做了一个虚拟的应用程序,应该是您的一个很好的例子。

我根据您的代码片段创建一个Message类;

//Message.h
@interface Message : NSObject {
    NSString *from_;
    NSString *date_;
    NSString *msg_;
}

@property (nonatomic, retain) NSString *from;
@property (nonatomic, retain) NSString *date;
@property (nonatomic, retain) NSString *msg;

-(NSDictionary *)dictionary;

@end

//Message.m
#import "Message.h"

@implementation Message

@synthesize from = from_;
@synthesize date = date_;
@synthesize msg = mesg_;

-(void) dealloc {
    self.from = nil;
    self.date = nil;
    self.msg = nil;
    [super dealloc];
}

-(NSDictionary *)dictionary {
    return [NSDictionary dictionaryWithObjectsAndKeys:self.from,@"from",self.date,    @"date",self.msg, @"msg", nil];
}

然后,我在AppDelegate中设置了两个消息的NSArray。诀窍在于,不仅顶层对象(您的情况下的通知)需要可序列化,而且通知所包含的所有元素也需要可序列化:这就是为什么我在Message类中创建了dictionary方法。

//AppDelegate.m
...
Message* message1 = [[Message alloc] init];
Message* message2 = [[Message alloc] init];

message1.from = @"a";
message1.date = @"b";
message1.msg = @"c";

message2.from = @"d";
message2.date = @"e";
message2.msg = @"f";

NSArray* notifications = [NSArray arrayWithObjects:message1.dictionary, message2.dictionary, nil];
[message1 release];
[message2 release];


NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON Output: %@", jsonString);

@end

因此,当我运行该应用程序时,输出为:

2012-05-11 11:58:36.018 stack [3146:f803] JSON输出:[{“ msg”:“ c”,“ from”:“ a”,“ date”:“ b”},{“ msg” :“ f”,“ from”:“ d”,“ date”:“ e”}]

原始答案:

这个你正在寻找的文件?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章