【问题标题】:objective-c json parser: How to parse a json file starting with a string and not brackets?objective-c json 解析器:如何解析以字符串而不是括号开头的 json 文件?
【发布时间】:2015-05-02 04:35:09
【问题描述】:

我有一个如下所示的 JSON 文件:

test.Data({
  "field": "try", 
  "date": "20150501", 
  "data": [
    "<sample1 code_date=\"2015050110\" type=\"play\"><sample2 name=\"foo\" place=\"bar\">"]
});

我尝试使用以下方法阅读它:

NSString *urlAsString = [NSString stringWithFormat:@"localhost"];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if ([data length] > 0 && connectionError == nil)
        _textLabel.stringValue = @"Good";
    else if ([data length] == 0 && connectionError == nil)
        _textLabel.stringValue = @"Nothing to load";
    else if (connectionError != nil)
        _textLabel.stringValue = connectionError.userInfo[@"NSLocalizedDescription"];


    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *e = nil;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error: &e];

        if (!jsonArray) {
            NSLog(@"Error parsing JSON: %@", e);
        } else {
            for(NSDictionary *item in jsonArray) {
                NSLog(@"Item: %@", item);
            }
        }
    });

但我收到以下错误:

解析 JSON 时出错:Error Domain=NSCocoaErrorDomain Code=3840“无法读取数据,因为它的格式不正确。” (字符 0 周围的值无效。) UserInfo=0x61800006e880 {NSDebugDescription=字符 0 周围的值无效。}

知道如何使用标准 JSON 解析器将这种 JSON 格式读入 Xcode 吗?

【问题讨论】:

  • 文件内容不是有效的 JSON,看起来更像是一个方法调用。
  • 更新服务器以返回有效的 JSON。
  • NSURLConnection 请求完成处理程序已经在后台线程上运行时,为什么还要使用dispatch_async 在另一个后台线程上运行该代码?
  • 我是这种方法的新手,我仍在阅读它。这部分代码来自一个教程。我想没有必要吧?

标签: ios objective-c json parsing


【解决方案1】:

我假设您想剥离方法调用并仅保留传递的 JSON 参数。如果您确定该文件只包含一个方法调用,而没有其他代码,尤其是带有花括号的代码,您可以应用以下逻辑:找到第一个和最后一个花括号,并使用该子字符串:

NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSUInteger firstCurlyBracePos = [dataString rangeOfString:@"{" options:0].location;
NSUInteger lastCurlyBracePos = [dataString rangeOfString:@"}" options: NSBackwardsSearch].location;
NSString jsonString = nil;
if(firstCurlyBracePos != NSNotFound && lastCurlyBracePos != NSNotFound) {
    jsonString = [dataString substringWithRange:NSMakeRange(firstCurlyBracePos, lastCurlyBracePos-firstCurlyBracePos)];
}

jsonString 将保存文件的 JSON 部分,如果两个花括号中的至少一个未找到,则为 nil

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多