从NSArray创建一个json字符串

rev*_*kpi 26 iphone json objective-c sbjson

在我的iPhone应用程序中,我有一个自定义对象列表.我需要从它们创建一个json字符串.我如何用SBJSON或iPhone sdk实现这个?

 NSArray* eventsForUpload = [app.dataService.coreDataHelper fetchInstancesOf:@"Event" where:@"isForUpload" is:[NSNumber numberWithBool:YES]];
    SBJsonWriter *writer = [[SBJsonWriter alloc] init];  
    NSString *actionLinksStr = [writer stringWithObject:eventsForUpload];
Run Code Online (Sandbox Code Playgroud)

我得到空的结果.

Thi*_*ama 55

这个过程现在非常简单,您不必使用外部库,这样做,(iOS 5及以上版本)

NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Run Code Online (Sandbox Code Playgroud)


Dam*_*amo 11

我喜欢我的类别所以我做这样的事情如下

@implementation NSArray (Extensions)

- (NSString*)json
{
    NSString* json = nil;

    NSError* error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    return (error ? nil : json);
}

@end
Run Code Online (Sandbox Code Playgroud)


小智 6

尽管投票率最高的答案对字典或其他可序列化对象数组有效,但对自定义对象无效。

这就是问题,您将需要遍历数组并获取每个对象的字典表示并将其添加到要序列化的新数组中。

 NSString *offersJSONString = @"";
 if(offers)
 {
     NSMutableArray *offersJSONArray = [NSMutableArray array];
     for (Offer *offer in offers)
     {
         [offersJSONArray addObject:[offer dictionaryRepresentation]];
     }

     NSData *offersJSONData = [NSJSONSerialization dataWithJSONObject:offersJSONArray options:NSJSONWritingPrettyPrinted error:&error];

     offersJSONString = [[NSString alloc] initWithData:offersJSONData encoding:NSUTF8StringEncoding] ;
 }
Run Code Online (Sandbox Code Playgroud)

至于Offer类中的dictionaryRepresentation方法:

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:self.title forKey:@"title"];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}
Run Code Online (Sandbox Code Playgroud)


Ven*_*enk 0

尝试这样,

- (NSString *)JSONRepresentation {
    SBJsonWriter *jsonWriter = [SBJsonWriter new];    
    NSString *json = [jsonWriter stringWithObject:self];
    if (!json)

    [jsonWriter release];
    return json;
}
Run Code Online (Sandbox Code Playgroud)

然后这样称呼它,

NSString *jsonString = [array JSONRepresentation];
Run Code Online (Sandbox Code Playgroud)

希望它能帮助你...

  • 上面的代码已损坏。要么它在 ARC 下编译失败,因为你调用了release,要么它会泄漏内存,因为你只有在 JSONify `self` 失败时才释放 writer。 (2认同)