iOS json字串轉化為NSArray(解析)
URL:http://www.12beli.com/App/Index/Category?pid=0 往伺服器發資料返回的是陣列
伺服器返回資料如下:
dict-123--{
CategoryName = Komputer;
ID = 4;
ParentID = 0;
child = "[{\"ID\":16,\"CategoryName\":\"Laptop\",\"ParentID\":4},{\"ID\":15,\"CategoryName\":\"Desktop\",\"ParentID\":4},{\"ID\":14,\"CategoryName\":\"Printer\",\"ParentID\":4},{\"ID\":24,\"CategoryName\":\"Aksesori Komputer\",\"ParentID\":4},{\"ID\":21,\"CategoryName\":\"Proyektor\",\"ParentID\":4},{\"ID\":204,\"CategoryName\":\"Networking\",\"ParentID\":4},{\"ID\":209,\"CategoryName\":\"Lain-Lain\",\"ParentID\":4},{\"ID\":215,\"CategoryName\":\"Hardware\",\"ParentID\":4}]";
}-
如要取child裡面的內容需要將json字串轉換,否則按正常取法的話會crash
參考:
NSMutableString *jsonDataString=[NSMutableString string];
[jsonDataString setString:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"jsonData" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil]];
NSData *nsData=[jsonDataString dataUsingEncoding:NSUTF8StringEncoding];
parsedArray=[NSJSONSerialization JSONObjectWithData:nsData options:kNilOptions error:nil];
我解析的內容 (ASIHTTPRequest)
- (void)requestFinished:(ASIHTTPRequest *)request
{
SBJSON * json = [[SBJSONalloc]init];
_dataArray = [jsonobjectWithString:[request responseString]error:nil];
if ([_dataArray
for (NSDictionary * dictin _dataArray) {
NSString *str= [dict objectForKey:@"child"];
NSData *nsData=[strdataUsingEncoding:NSUTF8StringEncoding];
NSArray *childArray=[NSJSONSerializationJSONObjectWithData:nsData options:kNilOptionserror:nil];
if ( childArray != nil ) {
// for(int i=0;i<[childArray count];i++)
// {
// [childArray objectAtIndex:i];
// }
for (NSDictionary * littleDictin childArray) {
NSString * name = [littleDict objectForKey:@"CategoryName"];
}
}
}
}
}