问题
I am facing an issue while converting an NSString to NSArray.
My string is :
["Default", "Discipleship", "Faith", "Family", "Hope",
"Life Building", "Love", "Missions", "Relationships"]
What i want to do is get the elements(Default,Discipleship etc.) out of this string and put them into an NSArray.
I have tried a lot but couldn't get it done, please help Any help would be great , thanks in advance
回答1:
First you convert your string to NSData:
NSString* str = @"[\"Default\",\"Discipleship\",\"Faith\",\"Family\",\"Hope\",\"Life Building\",\"Love\",\"Missions\",\"Relationships\"]";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
Then, you use:
NSError *e;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];
The object array contains the elements of the JSON text.
回答2:
NSString *list = @"Default,Discipleship,Faith,Family,Hope,Life Building,Love,Missions,Relationships";
NSArray *listItems = [list componentsSeparatedByString:@", "];
EDIT:
Please refer:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
for further understanding on NSString.
回答3:
try like this,first trim unwanted charecters and after that conver string into array.
NSString * strippedNumber = [yourString stringByReplacingOccurrencesOfString:@"[\"]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [val length])];
NSArray *array = [strippedNumber componentsSeparatedByString:@","];
回答4:
Try out this and for that need to add jsonkit and import josnkit.h in your class
NSString *responseString = [request responseString]
JKParseOptionFlags options = JKParseOptionComments | JKParseOptionUnicodeNewlines;
NSArray *responsArray=[responseString objectFromJSONStringWithParseOptions:options error:nil];
来源:https://stackoverflow.com/questions/17827070/how-to-convert-a-json-string-into-an-nsarray