【问题标题】:parse json feeds using jsonkit iOS [closed]使用 jsonkit iOS 解析 json 提要 [关闭]
【发布时间】:2011-09-18 08:03:13
【问题描述】:

我正在尝试使用在此处找到的 JSONKIt https://github.com/johnezang/JSONKit 来解析 JSON 提要并放入 Objective-c 对象中。我是 iOS 新手,真的不知道从哪里开始。有没有使用这个库的好教程?

【问题讨论】:

    标签: ios json ios4


    【解决方案1】:

    谷歌搜索后,我没有找到任何教程,但使用 JSONKit 应该是不言自明的。

    使用 NSURLConnection 或 ASIHTTPRequest 下载 JSON 提要后,只需创建 JSON 提要中所有对象的字典,如下所示:

    //jsonString is your downloaded string JSON Feed
    NSDictionary *deserializedData = [jsonString objectFromJSONString];
    
    //Helpful snippet to log all the deserialized objects and their keys
    NSLog(@"%@", [deserializedData description]);
    

    创建字典后,您可以简单地执行以下操作:

        NSString *string = [deserializedData objectForKey:@"someJSONKey"];
    

    这就是 JSONKit 背后的基础。

    当然,JSONKit 更强大,你可以在 JSONKit.h 中找到其他一些你可以用它做的事情

    【讨论】:

      【解决方案2】:

      我会小心地假设objectFromJSONString 返回一个NSDictionary,它可以很好地返回一个数组,或者nil,特别是如果服务器返回一些很少使用和想到的错误。

      更合适的操作是:

      NSError *error;
      id rawData = [jsonString objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
      
      if ( error != nil ) {
          // evaluate the error and handle appropriately
      }
      
      if ( [rawData isKindOfClass:[NSDictionary class]] ) {
          // process dictionary
      }
      else if ( [rawData isKindOfClass:[NSArray class]] ) {
          // process array
      }
      else {
          // someting else happened, 'rawData' is likely 'nil'
          // handle appropriately
      }
      

      如果没有这些检查,您很可能会遇到运行时错误,因为服务器返回了一些意外情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-14
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        相关资源
        最近更新 更多