我想用iOS 5中的AFNetworking框架解析从服务器收到的JSON数据:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
} failure:nil];我想要解析的JSON数据如下所示:
[ {
addressReal = "\U6912\U6c5f\U89e3\U653e\U5357\U8def295\U53f7";
areaTotal = 774;
balance = 0;
businessIncome = "556.49";
equNoString = "";
equStatusSting = "";
id = 208;
staff = 10;
},
{
addressReal = "\U53f0\U5dde\U5e02\U5e9c\U5927\U9053668\U53f7";
areaTotal = 156;
balance = 6463;
businessIncome = "174.93";
equStatusSting = "";
id = 209;
staff = 8;
}]现在如何访问JSON?
发布于 2013-02-27 17:23:36
这就是我所使用的,请随意根据您的需要进行调整:
-(void) loginWithUserID:(NSString*)usrID User:(NSString*)usr Password:(NSString *)psw Sender:(id)sender
{
if ([sender respondsToSelector:@selector(startLoading)]){
[sender performSelector:@selector(startLoading)];
}
baseURL = [NSString stringWithFormat:
@"http://xxx.xxx.xxx.xxx/test/service.svc/weblogin"];
NSString* serviceURL = [NSString stringWithFormat:
@"%@?userID=%@&user=%@&password=%@",baseURL,usrID,usr,psw;
NSURL *url = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.LoginOK = [JSON valueForKeyPath:@"LoginOK"];
if (LoginOK.intValue == 1) {
NSDictionary *usrData = [JSON valueForKeyPath:@"userData"];
userData = [[UserData alloc]init];
[userData readFromJSONDictionary:usrData];
NSLog(@"Userdata: %@",userData);
if ([sender respondsToSelector:@selector(loginSuccessful:)])
{
[sender performSelector:@selector(loginSuccessful:)];
}
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Correct Login Credentials" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
;}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
if ([sender respondsToSelector:@selector(stopLoading)]){
[sender performSelector:@selector(stopLoading)];
}
[[[UIAlertView alloc] initWithTitle:@"Error"
message:@"Loginservice not available! Check your connection!"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil] show];
NSLog(@"Error: %@", error);
}];
[operation start];
};并使用
-(void)readFromJSONDictionary:(NSDictionary *)d
{
[self setProperty1:[d objectForKey:@"property1"]];
}方法将该字典中的所有属性放入一个自定义类中。
因此,在您的情况下,它将使用
NSDictionary *data = [JSON valueForKeyPath:@"data"];https://stackoverflow.com/questions/15107650
复制相似问题