1

我的 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 信息和那些东西......但如果我试图获得个人价值,我无法得到它......请指导......

4

3 回答 3

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"]);
    }
}
于 2016-01-20T06:43:06.753 回答
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];
于 2012-07-20T12:35:39.033 回答
2

如果您想以这种方式使用 json,则需要将其解码为 anNSDictionary然后您可以在后半部分尝试使用它:

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

或者,如果您只需要"id"json 中标签下的文本,您可以执行以下操作:

label1.text = [json objectForKey:@"id"];
于 2012-07-20T12:35:48.560 回答