【问题标题】:Decode JSON to NSArray or NSDictionary将 JSON 解码为 NSArray 或 NSDictionary
【发布时间】:2012-04-12 10:20:48
【问题描述】:

我希望解码下面的JSON数据:

{
    "content":
    [   
        {
            "1":"a",
            "2":"b",
            "3":"c",
            "4":"d",
            "mark":"yes"
        }
    ]
}

不确定是放在 NSArray 还是 NSDictionary 中

欢迎评论

【问题讨论】:

标签: objective-c json


【解决方案1】:

您使用的是哪个 iOS 版本?在 iOS 5 中,您有 NSJSONSerialization 类来解析 JSON 数据,如果您需要针对较旧的 iOS 或 MAC OSX,您应该使用第三方库,例如 SBJSON。发布的字符串将是一个带有一个字典的数组的 NSDictionary。可以使用密钥 @"content"

访问该数组

在代码中:

NSString * jsonString = @"blblblblblb";
NSStringEncoding  encoding;
NSData * jsonData = [jsonString dataUsingEncoding:encoding];
NSError * error=nil;
NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

在 SWIFT 2.0 中:

    let jsonString = "blblblblblb"
    let encoding = NSUTF8StringEncoding
    let jsonData = jsonString.dataUsingEncoding(encoding)
    guard let jData = jsonData else {return}
    do {
        let parsedData = try NSJSONSerialization.JSONObjectWithData(jData, options: [])
    } catch let error {
        print("json error: \(error)")
    }

[更新] NSJSONSerialization 类也可用于 10.7 我的评论不正确。

【讨论】:

  • 对不起,标签是客观 c,顺便说一句,您使用了仅在 iOS5 上可用的类;-)
  • 没错,所以它不一定是 iOS。 NSJSONSerialization 在 OS X 10.7 中也可用。
  • NSJSONSerialization 在 OS X 10.7 中可用
【解决方案2】:

那个特定的字符串将解码成一个 NSDictionary,因为最外面的东西是一个 JSON 对象,它映射到我见过的每个 JSON 实现的 NSDictionary。如果要处理任意字符串,则需要测试返回的内容

NSError *jsonError;
id parsedThing = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (parsedThing == nil)
{
    // error
}
else if ([parsedThing isKindOfClass: [NSArray class]])
{
    // handle array, parsedThing can be cast as an NSArray safely
}
else
{
    // handle dictionary, parsedThing can be cast as an NSDictionary
    // NB only dictionaries and arrays allowed as long as NSJSONReadingAllowFragments 
    // not specified in the options
}

【讨论】:

    【解决方案3】:

    stringWithContentsOfFile:encoding:iOS<6 中已弃用

    iOS 6+

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"contents" ofType:@"json"];
    NSError * error=nil;
    NSString *jsonString = [NSString stringWithContentsOfFile:filePath encoding:nil error:&error];
    NSData * jsonData = [jsonString dataUsingEncoding:nil];
    NSArray * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    

    contents.json 文件在您的捆绑包中。

    【讨论】:

      【解决方案4】:

      您可以执行以下操作:

      NSData *data = ...; //JSON data
      NSError *jsonError = nil;
      [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
      

      您将返回一个NSDictionary,其中包含一个NSArray,其中包含一个包含五个NSString 对象的NSDictionary

      【讨论】:

        【解决方案5】:

        我使用了谷歌语音识别 API,我得到了一个无法在 iOS 上直接解析的 json 响应。结果样本如下:

        首先,我尝试说 Hello 1 2 3,这被识别为没有问题。 Json 响应是:

        {"result":[]}
        
        {"result":[{"alternative":[{"transcript":"hello 123","confidence":0.59780568},{"transcript":"hello 1 2 3"}],"final":true}],"result_index":0}
        

        或者说太久了,我得到了一个如下所示的 404 HTML:

        <html><title>Error 400 (Bad Request)!!1</title></html>
        

        当我胡言乱语时,我得到了:

        {"result":[]}
        

        所以为了解析所有这样的响应,我使用了下面的代码:

         NSString *msg = @"Could not synthesize !";
        
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"responseString: %@",responseString);
            if([responseString containsString:@"transcript"]&&responseString.length>25)
            {
        
                responseString = [responseString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];
        
                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        
                if(dictionary!=nil)
                    if(dictionary.allValues.count>0)
                    {
        
                        NSArray *array =[dictionary valueForKeyPath:@"result.alternative.transcript"];
        
                        if(array)
                        {
                            NSArray *array2 = [array objectAtIndex:0];
                            if(array2)
                            {
                                NSLog(@"%@",[array2 objectAtIndex:0] );
                                msg = [array2 objectAtIndex:0];
                            };
                        }
                    }
            }
        
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Google Response" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        

        希望这对某人有所帮助。

        【讨论】:

        • 在 iOS8 之前,if([responseString containsString:@"transcript"] &amp;&amp; responseString.length&gt;25) 行应改为:if ([responseString rangeOfString:@"transcript" options:NSCaseInsensitiveSearch].location != NSNotFound &amp;&amp; responseString.length&gt;25)
        猜你喜欢
        • 1970-01-01
        • 2011-01-14
        • 1970-01-01
        • 2011-10-16
        • 1970-01-01
        • 1970-01-01
        • 2010-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多