【问题标题】:SBJsonParser to store response from server in custom classSBJsonParser 将来自服务器的响应存储在自定义类中
【发布时间】:2012-02-05 15:05:01
【问题描述】:

我有一个 mySQL 数据库和一个 php 脚本,它从所述数据库返回一个表的内容。我将这些数据作为字符串保存,并且能够将其放入数组中,但我不太确定如何将其放入自定义 NSObject 类中。有什么办法可以做到吗?

【问题讨论】:

    标签: mysql ios arrays json class


    【解决方案1】:

    如果您的字符串是 JSON 对象数组,您可以使用 SBJsonParser 方法 objectWithString:,它将返回 NSDictionary 对象的 NSArray。然后您可以遍历您的数组并从数组中的每个元素创建一个自定义对象。使用 NSDictionary 方法objectForKey: 提取每个值。

    SBJsonParser *json = [[SBJsonParser new] autorelease];
    NSError *jsonError = nil;
    NSArray *parsedJSON = [json objectWithString:response error:&jsonError];            
    
    // this example just creates a custom object from the first element in the array
    NSDictionary dictionary = [parsedJSON objectAtIndex:0]           
    CustomObject *myCustomObject = [[CustomObject alloc] init];
    myCustomObject.firstname = [dictionary objectForKey:@"firstname"];
    myCustomObject.lastname = [dictionary objectForKey:@"lastname"];
    

    【讨论】:

    • 谢谢,很简单!所以要循环遍历表格,我只需将代码放在 for 循环中,然后将 0 更改为 i?
    • 谢谢。我试图只为表格的第一行做这件事,但我遇到了问题。当我运行NSLog(@"EVENT NAME: %@",[dictionary objectForKey:@"eventName"]); 时,我返回(空)。我正在异步获取请求,因此认为它可能没有时间获取数据。如果我将其更改为同步,则应用程序会因[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6b1f8b0' 而崩溃。有什么想法吗?
    • 你得到的 JSON 的结构是什么?如果 JSON 字符串不是数组(例如,如果数组包含在单个顶级节点中,例如 'events'),则 SBJsonParse 方法 objectWithString: 将改为返回一个 NSDictionary 对象,您首先需要从该对象提取数组。
    • 这是服务器的响应:{"eventsInfo":[{"eventID":"4","eventName":"Pop Tarts","eventAddress":"Students Union, Sheffield","eventPrice":"5","eventTime":"21:00:00","eventRating":"3","eventLogo":null},{"eventID":"5","eventName":"Space","eventAddress":"Octagon, SU, Sheffield","eventPrice":"4","eventTime":"21:00:00","eventRating":"5","eventLogo":null}]}
    • 啊,我想。所以你可以这样做:NSArray *parsedJSON = [(NSDictionary*)[json objectWithString:response error:&jsonError] objectForKey:@"eventsInfo"];
    猜你喜欢
    • 2020-04-21
    • 2019-02-19
    • 2014-12-20
    • 2011-01-26
    • 1970-01-01
    • 2019-05-02
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多