【问题标题】:iOS JSON Parse into NSDictionary and then NSArray with SBJsoniOS JSON 解析为 NSDictionary,然后使用 SBJson 解析为 NSArray
【发布时间】:2012-04-23 04:57:48
【问题描述】:

它应该很简单,但我无法让它工作。

Json 响应是 ([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4" }])

NSString *response = [request responseString];
//response is ([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}])

SBJSON *parser = [[[SBJSON alloc] init] autorelease];

NSDictionary *jsonObject = [parser objectWithString:response error:NULL];
// jsonObject doesn't have any value here..Am I doing something wrong?

NSMutableArray Conversion = [jsonObject valueForKey:NULL];
//Even if I get the value of jsonObject. I don't know what to put for valueForKey here

转换应该有两个 NSObjects..每个都应该有类似

id:1 x:1 y:2

id:2 x:2 y:4

【问题讨论】:

    标签: ios json parsing sbjson


    【解决方案1】:

    您的 JSON 解析器将从您的响应字符串生成 NSArray,而不是 NSDictionary。请注意,包括 SBJSON 在内的 JSON 解析器将返回数组对象或字典对象,具体取决于正在解析的 json 的内容。

    NSArray *jsonObject = [parser objectWithString:response error:nil];
    

    然后您可以访问数组中的各个项目(数组元素的类型为 NSDictionary)并使用valueForKey: 获取每个项目的属性。

    NSDictionary *firstItem = [jsonObject objectAtIndex:0];
    NSString *theID = [firstItem objectForKey:@"id"];
    

    【讨论】:

    • 尝试得到 jsonObject 的无效 CFArrayRef ..似乎 jsonObject 没有得到任何东西..我用断点检查并能够看到解析器得到了 json 值..
    • 我明白了.. 你的答案很完美:) 但是我得到的 Json 返回有 ( 和 ) 所以解析器无法处理它.. 我用 response = [response stringByReplacingOccurrencesOfString:@"(" withString 删除了:@""]; 和 response = [response stringByReplacingOccurrencesOfString:@")" withString:@""]; ** 然后它工作完美.. 谢谢.. :) 有没有一些简单的方法可以一次删除 '(' 和 ')'?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多