Could anyone tell me how to parse and extract just the data node, i.e. CM, Dozen, Foot..., from the JSON response below into an NSMutableArray, so it can be used as data source for UITableView?
{success: true, dataCount: 11, data:
[{"unitName":"CM"},{"unitName":"Dozen"},{"unitName":"Foot"},{"unitName":"Gross"},{"unitName":"Inch"},{"unitName":"K"},{"unitName":"KG"},{"unitName":"LB"},{"unitName":"Piece"},{"unitName":"Set"},{"unitName":"Yard"}]}
Thanks in advance for your help.
Cheers
Update...
Oli & Srika, You guys are so helpful!
Below is my code...
NSString *myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://192.168.0.100/myApp/getUnitInJson.php"]];
//myRawJson response is like below {success: true, dataCount: 5, data: [{"unitName":"CM"},{"unitName":"Dozen"},{"unitName":"Foot"},{"unitName":"Gross"},{"unitName":"Inch"}]} SBJsonParser *parser = [[SBJsonParser alloc] init]; NSArray *myParsedJson = [[parser objectWithString:myRawJson error:nil] copy]; NSArray *myExtractedData = [myParsedJson valueForKey:@"data"]; NSLog(@"RawJsonString: %@", myRawJson); // ouput: RawJsonString: {data:[{"unitName":"CM"},{"unitName":"Inch"},{"unitName":"Foot"},{"unitName":"Yard"},]} NSLog(@"myExtractedData Count: %@", [myExtrac开发者_如何学编程tedData count]); // output: myExtractedData Count: (null)There is nothing in myExtractedData. Am I doing anything wrong?
Please help.
Are you letting the user add/modify the array in the UITableView, is that why you need it to be mutable?
In any case, here's how you can do it: access the data array from the "wholeResponse" dictionary, then turn that array into a mutable one.
NSArray *data = [wholeResponse valueForKey:@"data"];
NSMutableArray *mutableData = [NSMutableArray arrayWithArray:data];
// Do something with the mutable data.
to get data
from the entire NSDictionary
-
NSArray values = [data objectForKey:@"data"]
.
This give the NSArray
associated with data
.
to get CM try this -NSString *CM = [[values objectAtIndex:0] objectForKey:@"unitName"]
The same goes for Dozen, Foot. etc.
You can then put this data in UITableView
.
UPDATE: Try this. I am assuming you are using this as JSON parser.
NSDictionary *myParsedJson = [myRawJson JSONValue];
NSArray *myExtractedData = [myParsedJson valueForKey:@"data"];
NSLog(@"myExtractedData Count: %@", [myExtractedData count]);
精彩评论