Savaş Zorlu
Savaş Zorlu

Reputation: 91

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.

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(@"HotelName : %@",hotelname);

This comes up in log:

[11437:f803] HotelName : ( "Blah Blah Hotel" )

And then the simulator crashes with the following error in log:

NSArrayI isEqualToString:]: unrecognized selector sent to instance

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.

Upvotes: 0

Views: 597

Answers (2)

Gabriel
Gabriel

Reputation: 3045

Check out this question. JSON is not an array, it's a dictionary.

- (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.

Upvotes: 0

Maverick1st
Maverick1st

Reputation: 3770

One option would be:

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

Upvotes: 1

Related Questions