从NSDictionary打印带有JSON对象的标签文本

时间:2012-07-20 12:31:11

标签: objective-c ios xcode json uilabel

我的json文件看起来像这样

[{"id":"1","category":"New Category1","title":"New Product2","description":"Please type a description1","imgurl":"http:\/\/s.wordpress.org\/about\/images\/wordpress-logo-notext-bg.png","spectitle":"Specification","specvalue":"Value"},{"id":"2","category":"Mobile","title":"Samsung","description":"Please type a description","imgurl":"http:\/\/s.wordpress.org\/about\/images\/wordpress-logo-notext-bg.png","spectitle":"Price","specvalue":"100$"}]

我有4个标签,必须在各个标签中打印id,类别,标题,描述。我已成功解析整个json对象并打印在单个标签中。我需要显示所有json对象及相应的类别对应标签

NSString *labelstring =[NSString stringWithFormat:@"%@",[json objectAtIndex:0]];
label1.text=[NSString stringwithformat: objectForKey:@"id"]; 
 label2.text=[NSString stringwithformat:objectForKey:@"category"];
 label3.text=[NSString stringwithformat:objectForKey:@"title"];  
 label4.text=[NSString stringwithformat:objectForKey:@"description"]; 

这里json是NSArray的一个变量,有URL信息和那些东西......但如果我试图获得个人价值,我就无法得到它......指导请...

3 个答案:

答案 0 :(得分:5)

(void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://advantixcrm.com/prj/mitech/index.php/api/appconfig/Mg"]];

    [request setHTTPMethod:@"GET"];

    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

    NSError *err;
    NSURLResponse *response;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];

    NSArray *array=[jsonArray objectForKey:@"info"];

    for (int i=0; i<[array count]; i++) {
        _label.text = [[array objectAtIndex:i]objectForKey:@"restaurant_location"]);
    }
}

答案 1 :(得分:4)

您是否正在展示您的真实代码? [NSString stringwithformat:objectForKey:@"id"];语法无效。你有没有错误?

正确的代码:

// ??? NSString *labelstring = [NSString stringWithFormat:@"%@",[json objectAtIndex:0]];
NSDictionary *dict = [json objectAtIndex:0];
label1.text = [dict valueForKey:@"id"]; 
label2.text = [dict valueForKey:@"category"];
label3.text = [dict valueForKey:@"title"];  
label4.text = [dict valueForKey:@"description"];

编辑:我不知道你是否以正确的方式解析你的JSON,所以也是这样:

NSData *jsonData = ...
NSArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

答案 2 :(得分:2)

如果你想以这种方式使用json,你需要将它解码为NSDictionary然后你可以按照你在下半部分尝试的方式使用它:

label1.text = [NSString stringwithFormat:@"%@", [json objectForKey:@"id"]];

或者如果你只需要json中"id"标签下的文字,你可以这样做:

label1.text = [json objectForKey:@"id"];