gpt4 book ai didi

objective-c - 我如何在 JSONKit 中对 NSDate 字典进行 JSON 序列化

转载 作者:技术小花猫 更新时间:2023-10-29 11:04:49 29 4
gpt4 key购买 nike

我尝试使用 Jsonkit 和 Apple 的 JSON 序列化程序,但没有成功。它不断打破 geo 属性,这是一个 NSNumbers 的 nsarray。

Post* p = [[Post alloc] init];

p.uname = @"mike";
p.likes =[NSNumber numberWithInt:1];
p.geo = [[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:37.78583], [NSNumber numberWithFloat:-122.406417], nil ];
p.place = @"New York City";
p.caption = @"A test caption";
p.date = [NSDate date];


NSError* error = nil;

NSString* stuff = [[p getDictionary] JSONStringWithOptions:JKParseOptionNone error:&error];

更新:检查错误是它失败的 NSDate,而不是 NSArray。如何将日期格式化程序传递给函数?

更新 2:已解决 - 好的,查看了 jsonkit 的最新提交,发现您可以这样做:

 NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];

NSString* result = [p.dictionary JSONStringWithOptions:JKSerializeOptionNone serializeUnsupportedClassesUsingBlock:^id(id object) {
if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
return(nil);
} error:nil];

这似乎已经奏效,但请注意,JSONKit 的此功能是 WIP,因此它可能会在下一个正式版本中更改。

最佳答案

嗯——不能代表 JSONKit 或 iOS5——我使用 Stig 的 SBJSON框架。使用它,实现相当简洁:

@implementation Post

- (id) initWithName:(NSString*)Name :(NSNumber*)Likes :(NSArray*)Geo :(NSString*)Place :(NSString*)Caption :(NSDate*)Date {

if ((self=[super init])==nil) {
return nil;
}
uname = Name;
likes = Likes;
geo = Geo;
place = Place;
caption = Caption;
date = Date;
return self;
}

- (NSDictionary*) getAsDictionary {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:uname,@"uname",
likes,@"likes",
geo,@"geo",
place,@"place",
caption,@"caption",
dateString,@"date",
nil];
return dict;
}

@end

- (void)viewDidLoad {
[super viewDidLoad];

Post* post = [[Post alloc] initWithName:@"Mike"
:[NSNumber numberWithInt:1]
:[[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:37.78583], [NSNumber numberWithFloat:-122.406417],nil]
:@"New York City" :@"A Test caption"
:[NSDate date]];

SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString* json = [writer stringWithObject:[post getAsDictionary]];
if (json == nil) {
NSLog(@"error = %@",writer.errorTrace);
}
NSLog(@"json = %@",json);
[writer release];
[post release];
}

产生

TestJSON[52337:207] json = {"likes":1,"date":"2011-12-13 11:12:57","place":"New York City","caption":"A Test caption","uname":"Mike","geo":[37.78583,-122.4064]}

关于objective-c - 我如何在 JSONKit 中对 NSDate 字典进行 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8494149/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com