How to parse JSON in objective-C iOS

泄露秘密 提交于 2019-12-13 22:17:23

问题


I want to parse JSON in Objective-C in iOS using AFNetworking library

{
  "success": 1,
  "row": [
    {
      "amount": 2800
    }
   ]
}

CODE -

 arrAmount = [responseObject valueForKey:@"row"];
 NSLog(@"%@",arrAmount);

 NSString *strAmount =[NSString stringWithFormat:@"%@", [arrAmount valueForKey:@"amount"]];

 self.lblAmount.text =[NSString stringWithFormat:@"%@",strAmount];

回答1:


Response of rowcontain array not Dictionary, so access amount from first object of Array.

NSarray *arrAmount = [responseObject objectForKey:@"row"];
if arrAmount.count > 0 {
    NSDictionary *dic = [arrAmount objectAtIndex:0];
    NSString *strAmount = [NSString stringWithFormat:@"%d", [dic objectForKey:@"amount"]];
    self.lblAmount.text = strAmount;
}



回答2:


use NSDictionary:

NSDictionary *dict = [responseObject valueForKey:@"row"];
NSLog(@"value = %@",[dict valueForKey:@"amount"]);  // fetch amount value

array = [dict valueForKey:@"amount"];   // // fetch all amount value in array
NSLog(@"array = %@", array.description);



回答3:


Use objectForKey instead of valueForKey

NSDictionary *responseObject;
NSArray *arrAmount;
arrAmount = [responseObject objectForKey:@"row"];
NSLog(@"%@",arrAmount);
NSString *strAmount =[NSString stringWithFormat:@"%@", [[arrAmount objectAtIndex:0] objectForKey:@"amount"]];


来源:https://stackoverflow.com/questions/39487854/how-to-parse-json-in-objective-c-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!