无法将NSDictionary值转换为json

时间:2014-02-13 14:25:17

标签: ios objective-c json nsdictionary nsjsonserialization

我有NSDictionary值,我想将其转换为Json字符串,如:

{
    body = "10-feb";
    comments =     (
    );
    complete = 1;
    "created_at" = "2014-02-09T15:56:01Z";
    "due_at" = "2014-01-10 20:00:00 +0000";
    "due_on" = "2014-10-02";
    id = 439824;
    "notification_sent" = 0;
    "notify_user" = 0;
    "organization_id" = 972;
    participants =     (
    );
    reminders =     (
    );
    starred = 0;
    "updated_at" = "2014-02-09T15:56:01Z";
    "user_id" = 11129;
}

我将它转换为json的方式是:

- (NSString*) jsonStringWithPrettyPrint:(BOOL) prettyPrint str:(NSDictionary *)str {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str
                                                       options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
        return @"{}";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}

我不知道为什么它总是无法转换。?

1 个答案:

答案 0 :(得分:5)

传递到NSJSONSerialization的对象只能包含NSDictionaryNSArrayNSStringNSNumberNSNull

必须先使用NSDate

NSStrings个对象明确转换为NSDateFormatter