如何解析Objective-C iOS中的JSON

时间:2016-09-14 10:12:02

标签: ios objective-c json parsing afnetworking

我想使用AFNetworking库在iOS中的Objective-C中解析JSON

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

代码 -

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

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

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

3 个答案:

答案 0 :(得分:2)

row的响应包含数组而不是Dictionary,因此从数组的第一个对象访问数量。

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;
}

答案 1 :(得分:1)

使用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);

答案 2 :(得分:0)

使用objectForKey代替valueForKey

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