ios - 将 iOS objective-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 堆栈[3146:f803] JSON 输出:[ { “消息”:“c”, “从”:“一个”, “日期”:“b” }, { “消息”:“f”, “来自”:“d”, “日期”:“e” } ]

原始答案:

是 this您要查找的文档?

关于ios - 将 iOS objective-c 对象转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10548429/

相关文章:

json - 将参数传递给 jq 过滤器

Java - 嵌套在嵌套中的 Gson 解析

java - 如何使用 Jackson 定义可选的 json 字段

java - 为什么 Json 测试程序不起作用?

python - 如何以人类可读的格式序列化 Python 对象?

c# - ASP.NET web api 无法获取 application/x-www-form-u

java - 如何使用 Java 和 Jackson 库对 Json 字符串进行多态反序列化?

php - 如何在 symfony 中返回 json 编码格式错误

xml - CSV、JSON 和 XML 对于 REST API 的相对优点是什么?

javascript - 定义 "cyclic data structures"