我正在使用下面的json方法和以下代码来解析json方法并在标签上显示我需要的数据。 我跟着这个链接http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json/和许多其他链接,但我没有得到我需要的结果。它在下面的代码行中抛出异常,否则它显示空值。
NSDictionary* profile = [profileinfo objectAtIndex:0]; //throws exception
任何人都可以帮我解决下面的代码中出现的问题以及缺少的内容,以便获得json方法中的值,即phonenumber,firstname和其他数据。
//Json Method
{
"createdBy":"superadmin",
"createdOn":"2011-11-15T00:49:06+05:30",
"updatedBy":"superadmin",
"updatedOn":"2011-11-15T00:49:06+05:30",
"contactNumber":"9945614074",
"emailNotification":"true",
"firstName":"resident2",
"lastName":"user5",
"loginId":"jin",
"married":"false",
"message":"",
"preferredLanguage":"ko_KR",
"sex":"0",
"smsNotification":"false",
"status":"ACTIVE",
"subscribedPlans":"Intelligent Concierge",
"userName":"Cisco"
}
//code
- (void)loadData
{
dataWebService = [[NSMutableData data] retain];
NSURLRequest *request = [[NSURLRequest requestWithURL:[NSURL URLWithString:@"URL LINK"]]retain];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
self.dataWebService = nil;
NSArray* profileinfo = [(NSDictionary*) [responseString JSONValue] objectForKey:@"createdBy"];
[responseString release];
NSDictionary* profile = [profileinfo objectAtIndex:0];
//fetch the data
NSNumber* numb = [profile objectForKey:@"contactNumber"];
NSString* name = [profile objectForKey:@"firstName"];
//set the text to the label
label.numberOfLines = 0;
label.text = [NSString stringWithFormat:@"contactNumber: %@ \n \n Name: %@ \n \n",
numb,name];
}
答案 0 :(得分:1)
jsonValue是你的字典。
替换
NSArray* profileinfo = [(NSDictionary*) [responseString JSONValue] objectForKey:@"createdBy"];
和
NSDictionary* profile = [profileinfo objectAtIndex:0];
带
NSDictionary * profile = (NSDictionary*)[responseString JSONValue];
现在使用objectForKey来获取值