从NSArray创建一个json字符串

时间:2013-07-23 12:14:42

标签: iphone objective-c json 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];

我得到空的结果。

6 个答案:

答案 0 :(得分:54)

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

NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

答案 1 :(得分:10)

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

@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

答案 2 :(得分:5)

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

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

 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] ;
 }

对于Offer类中的dictionaryRepresentation方法:

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

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

答案 3 :(得分:2)

试试这个Swift 2.3

let consArray = [1,2,3,4,5,6]
var jsonString : String = ""
do
{
    if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(consArray, options: NSJSONWritingOptions.PrettyPrinted)
    {
        jsonString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
    }
}
catch
{
    print(error)
}

答案 4 :(得分:0)

试试这个,

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

    [jsonWriter release];
    return json;
}

然后称之为,

NSString *jsonString = [array JSONRepresentation];

希望它会帮助你......

答案 5 :(得分:0)

我参加这个聚会有点晚了,但你可以通过在自定义对象中实现-proxyForJson方法来序列化一系列自定义对象。 (或者在自定义对象的类别中。)

对于example