简体   繁体   中英

Getting element from NSString

my app get data from a php web service and return a NSString

["first name","last name","adress","test@test","000-000-0000","password","code","0"]

How can i get the second element ?

This is a JSON formatted string which you are getting from your web service.

You must be getting bytes from server. Just replace your variable which have bytes stored with my variable " response data ".

Code:

NSError* error;
    NSArray* myResultArray = [NSJSONSerialization 
        JSONObjectWithData:responseData options:kNilOptions error:&error];

You will get an array in variable " myResultArray " and you can get all value by index.

Code:

NSString* first name = [myResultArray objectAtIndex:0];

What you have given here is an array and not a string. May be you could provide more details like the exact response and the code that you are trying here.

To Convert a JSON string to NSDictionary all you need to do is:

NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                 options:nil 
                                    error:&jsonError];

And to NSArray :

NSArray *array = [NSJSONSerialization JSONObjectWithData:objectData options:nil error:&jsonError];
NSString *secondElement = array[1];

That web service doesn't return an NSString. It runs data in some format defined by the service, and you convert it to an NSString. Find out what the format actually is, then convert it appropriately, for example using NSJSONSerialization.

The example string your showed here seems wired. This looks more like a array than string. If this is a NSArray then you can do it like this:

NSArray *data = @[@"first name",@"last name", @"adress", @"test@test", @"000-000-0000", @"password", @"code", @"0"];
NSLog (@"Second component = %@", data[1]);

However, if you anticipate this as NSString then this is how you would handle this:

NSString *test = @"[\"first name\",\"last name\",\"adress\",\"test@test\",\"000-000-0000\",\"password\",\"code\",\"0\"]";
NSLog (@"Second component = %@", [test componentsSeparatedByString:@","][1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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