我如何在iOS中解析json

时间:2013-06-16 14:54:37

标签: ios json parsing

我有以下JSON!

这个JSON写了我的熊醉伏特加酒:D

{
    "Label": [ 1, 2, 3, 4, 5 ],
    "ViewId": 1
}

代码:

NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];  
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (int i=0; i < json.count; i++)
{
    NSString * FRid = [[json objectAtIndex:i] objectForKey:@"ViewId"]; //it's work
    NSString * FRName = [[json objectAtIndex:i] objectForKey:@"Label"]; //it's don't work   Out of scope

如何从“Label”获取数据到NSString?

2 个答案:

答案 0 :(得分:0)

尝试:

NSString * FRid = [[json objectAtIndex:i] objectForKey:@"ViewId"]; 
NSArray * FRName = [[json objectAtIndex:i] objectForKey:@"Label"]; 

* Label Key包含一个数组,而不是一个字符串。

在此之后,您可以通过以下方式将数组转换为字符串,

NSString *FRNameString = [FRName componentsJoinedByString:@", "];

答案 1 :(得分:0)

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSArray *label = [dict objectForKey:@"Label"];

//convert to string

NSString *final = [[NSString alloc]init];
for (NSString * string in label){
    final = [NSString stringWithFormat:@"%@%@", final, string];
}
NSLog(@"%@",final);

这是非常接近的伪代码

我在手机上写了这个,所以我不能格式化为代码。