简体   繁体   English

如何从json数组中提取键值并将其传递给变量以分配给标签?

[英]How do you extract a key value from a json array and pass it to a variable to assign to a label?

I've got an array populated with json. 我有一个用json填充的数组。

rows4 = [dict objectForKey:@"users"];

I have the following line that parses a key value from it. 我有以下一行从中解析键值。

NSString *hotelname = (NSString *) [rows4 valueForKey:@"H_NAME"];

I then assign the value to a label in the view with the following line: 然后,使用以下行将值分配给视图中的标签:

LabelName.Text= hotelname;

Everything seems fine upto here. 到这里一切似乎都很好。 I write the log with Nslog as follows : 我用Nslog编写日志,如下所示:

NSLog(@"HotelName : %@",hotelname);

This comes up in log: 这出现在日志中:

[11437:f803] HotelName : ( "Blah Blah Hotel" ) [11437:f803] HotelName :(“布拉赫布拉酒店”)

And then the simulator crashes with the following error in log: 然后模拟器崩溃,并在日志中显示以下错误:

NSArrayI isEqualToString:]: unrecognized selector sent to instance NSArrayI isEqualToString:]:无法识别的选择器已发送到实例

What I understand from this is the variable that I assign to the label is actually not a variable but it is an array. 我从中了解到的是我分配给标签的变量实际上不是变量,而是一个数组。 Am I right? 我对吗? If so, how can I extract a single value from my variable with the help of a key and assign it to a variable which then I can assign to a label? 如果是这样,如何在键的帮助下从变量中提取单个值并将其分配给变量,然后可以将其分配给标签?

I am using touchJSON btw. 我正在使用touchJSON btw。

One option would be: 一种选择是:

if(hotelname.count > 0)    
    LabelName.Text= [hotelname objectAtIndex:0];

Check out this question . 看看这个问题 JSON is not an array, it's a dictionary. JSON不是数组,而是字典。

- (void)viewDidLoad {
        //below is a function from [this tutorial][2]
    [super viewDidLoad];
    NSString *jsonString = [NSString stringWithString:@"{\"foo\": \"bar\"}"];
    NSDictionary *dictionary = [jsonString JSONValue];
    NSLog(@"Dictionary value for \"foo\" is \"%@\"", [dictionary objectForKey:@"foo"]);

        //This is your code, just changed some stuff...

        NSString *hotelname = (NSString *) [jsonString valueForKey:@"?"];
        LabelName.Text= hotelname;
}

Hope this helped, cheers. 希望这会有所帮助,欢呼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM