Fadielse Fadielse - 2 months ago 19
JSON Question

How to convert json to NSArray

I have a JSON array being output on a page. I would like to convert this JSON array into an NSArray.

enter image description here

Or convert this json like :
enter image description here

Can someone let me know what the step might be? Thank you!

Answer

Try this.

NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:0   error:nil];

Or

NSArray * json = [self JSONWithData:data];

+(id)JSONWithData:(NSData *)data
{
    if (!data)
    {
        return nil;
    }

    id json = [NSJSONSerialization JSONObjectWithData:data
                                              options:0
                                                error:nil];
    if (!json)
    {
        // try to clean response
        NSString * dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (!dataString)
        {
            dataString = [[NSString alloc] initWithData:data encoding:NSWindowsCP1251StringEncoding];
        }
        NSRange rangeDict = [dataString rangeOfString:@"{"];
        NSRange rangeArray = [dataString rangeOfString:@"["];
        NSRange range = rangeDict;
        if ((rangeDict.location == NSNotFound) || (rangeArray.location != NSNotFound && rangeArray.location < rangeDict.location))
        {
            range = rangeArray;
        }

        if (range.location != NSNotFound)
        {
            dataString = [dataString substringFromIndex:range.location];
            NSError * error = nil;
            if ([dataString length])
            {
                json = [NSJSONSerialization JSONObjectWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding]
                                                       options:0
                                                         error:&error];
                if (!json)
                {
                    dataString = [dataString stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
                    error = nil;
                    json = [NSJSONSerialization JSONObjectWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:0
                                                             error:&error];
                }
                if (!json)
                {
                    dataString = [dataString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    error = nil;
                    json = [NSJSONSerialization JSONObjectWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:0
                                                             error:&error];
                }
            }
            if (json)
            {
                NSLog(@"Response cleaned");
            }
            else
            {
                NSLog(@"Failed to parse JSON: %@", [error localizedDescription]);
            }
        }
    }

return json;
}

And use it like:

if (json) {
    if ([json count] > 0) {
        NSString * name = json[0]["name"]
        if (name) {

        }
        NSArray *arrayContent = json[0]["array_content"]
    }
}

For Swift 3.0

extension JSONSerialization {
    final class func jsonObject(with data: Data) -> Any? {
        do {
            var data = data
            if !data.isEmpty, let txt = String(data: data, encoding: .utf8) {
                let newTxt = txt.replacingOccurrences(of: "\\", with: "\\\\")
                if let data_ = newTxt.data(using: .utf8) { data = data_ }
            }
            return try jsonObject(with: data, options: [])
        } catch { return nil }
    }
}

guard let json = JSONSerialization.jsonObject(with: data) as? AnyObject else { return }
Comments