我使用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];
}

产生

10-08 03:18