How to convert a JSON String into an NSArray? [closed]

五迷三道 提交于 2019-12-07 05:55:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!