iPhone中的JSON解析器问题?

时间:2013-01-28 07:24:12

标签: iphone ios json parsing sbjson

JSON响应如 - {“response”:{“成功”:“Y”,“项目”:[{“userid”:“255”}]}}

我试着像这样解析:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *jsonStr = [[NSString alloc] initWithData:mutaebleData encoding:NSUTF8StringEncoding];
    NSLog(@"JSonSTr : %@", jsonStr);

    SBJSON *json = [[SBJSON alloc]init];

    NSDictionary *dic = (NSDictionary *) [json objectWithString:jsonStr];
    NSDictionary *dic1 = (NSDictionary *) [dic objectForKey:@"response"];
    NSDictionary *dic2 = (NSDictionary *) [dic1 objectForKey:@"Success"];
    NSDictionary *dic3 = (NSDictionary *) [dic1 objectForKey:@"items"];

    NSDictionary *dic4 = (NSDictionary *) [dic3 objectForKey:@"userid"]; // App crash in this line
}

如何获取用户ID值?请帮帮我

先谢谢

4 个答案:

答案 0 :(得分:2)

这是问题所在:

 NSDictionary *dic4 = (NSDictionary *) [dic3 objectForKey:@"userid"];

您应该使用:

NSDictionary *dic4 = (NSDictionary *) [[dic3 objectAtIndex:0] objectForKey:@"userid"];

答案 1 :(得分:0)

试试这个

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

NSString *jsonStr = [[NSString alloc] initWithData:mutaebleData encoding:NSUTF8StringEncoding];
NSLog(@"JSonSTr : %@", jsonStr);

SBJSON *json = [[SBJSON alloc]init];

NSDictionary *dic = (NSDictionary *) [json objectWithString:jsonStr];
NSDictionary *dic1 = (NSDictionary *) [dic objectForKey:@"response"];
NSDictionary *dic2 = (NSDictionary *) [dic1 objectForKey:@"Success"];
NSArray *arr3 = (NSArray *) [dic1 objectForKey:@"items"];

NSString *str = [[arr objectAtIndex:0]objectForKey:@"userid"];
NSlog(@"userid ==%@",str);
// NSDictionary *dic4 = (NSDictionary *) [dic3 objectForKey:@"userid"]; // App crash in this line
 }

希望它有所帮助...

答案 2 :(得分:0)

您可以添加SBJSON框架文件。并通过解析by

NSDictionary *responseDict = [response JSONValue];
just parse it as normal dictionary.

NSString *userIDValue=[NSString stringWithFormat:@"%@",[[[[responseDict valueForKey:@"response"]valueForKey:@"items"]objectAtIndex:0]valueForKey:@"userid"]];

检查一下。

答案 3 :(得分:-1)

NSDictionary *dic = (NSDictionary *) [json objectWithString:jsonStr];
 NSDictionary *dic1 = (NSDictionary *) [dic objectForKey:@"response"];
 NSDictionary *dic2 = (NSDictionary *) [dic1 objectForKey:@"Success"];
 NSDictionary *dic3 = (NSDictionary *) [dic1 objectForKey:@"items"];

 for(NSDictionary *str in dic3)
 {
    NSLog(@"str:%@",[str valueForKey:@"userid"]);
 }

希望有所帮助