create a json string from NSArray

喜你入骨 提交于 2019-11-28 19:13:53

This process is really simple now, you don't have to use external libraries, Do it this way, (iOS 5 & above)

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

I love my categories so I do this kind of thing as follows

@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

Although the highest voted answer is valid for an array of dictionaries or other serializable objects, it's not valid for custom objects.

Here is the thing, you'll need to loop through your array and get the dictionary representation of each object and add it to a new array to be serialized.

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

As for the dictionaryRepresentation method in the Offer class:

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

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}
Mohammad Kamran Usmani

Try like this 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)
}

Try like this,

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

    [jsonWriter release];
    return json;
}

then call this like,

NSString *jsonString = [array JSONRepresentation];

Hope it will helps you...

Stig Brautaset

I'm a bit late to this party, but you can serialise an array of custom objects by implementing the -proxyForJson method in your custom objects. (Or in a category on your custom objects.)

For an example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!