0

hi i have this string { "data": [ { "name": "Lorena Trujillo", "id": "500144123" }, { "name": "George Arcila", "id": "520311359" }, { "name": "Laura Victoria Mu\u00f1oz Rincon", "id": "528543677" }, { "name": "Camilo Andres Santacoloma Mejia", "id": "529547832" }],"paging": { "next": "https://graph.facebook.com/537223119/friends?access_token=AAAAAAITEghMBAI7cZBdbAHt3ZC24esi4ZA6O6kFdwU1H0ekDmGQGRZCUZAVW3T6W6fzg50jHsdfsdfsfdsfdsfzdixf1RrTFLzV96ZBWXAZDZD&limit=5000&offset=5000&__after_id=1000456456455" }

}

and y need extract the substring between [ and ] i use the next code

NSRange startRange = [strFriends rangeOfString:@"["];
NSRange endRange = [strFriends rangeOfString:@"]"];
NSString *formData = [strFriends  substringWithRange:NSMakeRange(startRange.location,endRange.location)];
NSLog(@"this is the data %@",formData); 

and the result is

[ { "name": "Lorena Trujillo", "id": "500144123" }, { "name": "George Arcila", "id": "520311359" }, { "name": "Laura Victoria Mu\u00f1oz Rincon", "id": "528543677" }, { "name": "Camilo Andres Santacoloma Mejia", "id": "529547832" }],"pagin

any idea why these last characters appear ,"pagin thank you very much

2 Answers2

2

This is because startRange location and endRange location both point to the location within the string - but subStringWithRange takes a location and a length - so you need to calculate the length of the string you want to extract. Like this:

NSUInteger dataLength = endrange.location - startRange.location;
NSString *formData = [strFriends  substringWithRange:NSMakeRange(startRange.location,dataLength)];

Besides that, you really need a JSON parser for parsing JSON. Picking out small substrings like this is going to be a lot of work and brittle.

driis
  • 161,458
  • 45
  • 265
  • 341
  • Absolutely: When you use JSON, use the JSON parser. Whatever hand written code you use, it will take me two minutes to produce input that your code won't handle correctly. Promised. And your company's customers will find out the hard way. Less than two minutes. Just a user who uses as his name "Jim [Joe's best friend]". – gnasher729 Feb 27 '14 at 13:09
2

As driis mentioned in the comments you should use a JSON parser to handle this data. To answer your question you are seing "pagin" because a range has a location and a length not 2 locations. Try

NSMakeRange(startRange.location,endRange.location - startRange.location)
Joe
  • 56,979
  • 9
  • 128
  • 135