栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

我根据您的代码片段创建一个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”}]

原始答案:

是这个你正在寻找的文件?



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413680.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号