How to convert json to NSArray [duplicate]

风格不统一 提交于 2020-01-17 21:36:20

问题


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

Or convert this json like :

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


回答1:


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, checkEscapeSymbols: Bool = false) -> Any? {
        do {
            var data = data
            if !data.isEmpty, let txt = String(data: data, encoding: .utf8) {
                var newTxt = txt.replacingOccurrences(of: "\\", with: "\\\\")
                newTxt = newTxt.replacingOccurrences(of: "\\\\/", with: "\\/")
                newTxt = newTxt.replacingOccurrences(of: "\\\\\"", with: "\"")
                newTxt = newTxt.replacingOccurrences(of: "\\\"", with: "\"")
                newTxt = newTxt.replacingOccurrences(of: "\\\\'", with: "\\'")
                if checkEscapeSymbols {
                    newTxt = newTxt.replacingOccurrences(of: "\0", with: "\\0")
                    newTxt = newTxt.replacingOccurrences(of: "\r", with: "\\r")
                    newTxt = newTxt.replacingOccurrences(of: "\n", with: "\\n")
                    newTxt = newTxt.replacingOccurrences(of: "\t", with: "\\t")
                }
                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 }


来源:https://stackoverflow.com/questions/36617868/how-to-convert-json-to-nsarray

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