how to parse array of objects using json for iphone - iphone

I have a problem parsing the array of objects from the JSON result.
[
{
"first_name":"vijay",
"last_name":"last",
"creditCardNumber":"178978977779787979",
"month":"02","year":"2012",
"address":"Addres2"
}
{
"first_name":"vijay",
"last_name":"last",
"creditCardNumber":"178978977779787979",
"month":"02","year":"2012",
"address":"Addres2"
}
{
"first_name":"vijay",
"last_name":"last",
"creditCardNumber":"178978977779787979",
"month":"02","year":"2012",
"address":"Addres2"
}
]
I wish to extract creditCardNumber value from all objects in the array.

Google "JSON Framework". Follow the (easy) instructions to install it.
Then go:
//let's say there's NSString *jsonString.
NSArray *userData = [jsonString JSONValue];
NSMutableArray *creditCards = [NSMutableArray array];
for (NSDictionary *user in userData) {
[creditCards addObject:[user objectForKey:#"creditCardNumber"]];
}
You'll drop out the bottom of that with NSMutableArray *creditCards full of NSString objects containing the credit card numbers.

#Dan Ray answer is correct, but if you want to avoid third-party librairies you can use NSJSONSerialization:
Assuming that NSData *responseData is containing your JSON.
NSArray *userData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSMutableArray *creditCards = [NSMutableArray array];
for (NSDictionary *user in userData) {
[creditCards addObject:[user objectForKey:#"creditCardNumber"]];
}
Source: NSJSONSerialization.

Related

How to parse api response on table view?

My json response data formate as :-
[{"0":"1","id":"1","1":"Pradeep","name":"Pradeep","2":null,"sender":null,"3":null,"
So to parse the "name" on table view?
My own implementation is:-
I am new in ios development please help me
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData
options:0 error:nil]; // response saved in allDataDictionary
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"]; // feeds entry
NSArray *feedforentry=[feed objectForKey:#"entry"];
for(NSDictionary *diction in feedforentry)
{
NSDictionary *title=[diction objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self JustConfesstable]reloadData]; // reload table
}
First of all get data in Dictionary and then store what you want in NSArray.. using Keys
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSLog(#"%#",delegate.firstArray);
NSArray * responseArr = json[#"Deviceinfo"];
NSArray * firstarray=[[NSArray alloc]init];
for(NSDictionary * dict in responseArr)
{
[firstarray addObject:[dict valueForKey:#"name"]];
}
first array contains names.. what you want from that json response.
and then pass that data to tablview. what you want to do here you get the array of name data.
You need to use JSON parser. I will recommend: https://github.com/johnezang/JSONKit
With that you can do:
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSError *error = nil;
id objectFromJson = [jsonKitDecoder objectWithData:data error:&error];

iOS - How to print value in textfield using delegate

I am new to iOS. I have some problem do you have some solution for it? I am not able to print the json value in textfield
This is my contactViewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
fname.text=#"Hello";
}
After the view is loaded hello value is shown in the text box, but when I call list button to get the json values:
-(IBAction)list:(id)sender{
vedant=[[WebserviceViewController alloc]init];
[vedant listContacts];
}
Then from webserviceViewController.m I pass the jsonResponse to the same file i.e contactViewController.m and parse the json value and print it but it does not shows the value in text field
-(void)allContacts:(NSString *)JSONResponse{
NSLog(#"%#",JSONResponse);
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
int accCount =[json count];
for(int i=0;i<accCount;i++){
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
// NSLog(#"%#",JSONResponse);
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
NSString *firstName = [NSString stringWithFormat:#"%#", [[json objectAtIndex:i] objectForKey:#"first_name"]];
NSLog(#"%#",firstName); //this prints the actual first name in console But
fname.text=firstName;
NSLog(#"%#",fname.text); //it prints "(Null)" in console
}
}
Do I need to create delegate to pass value?
Yes, then any help of creating such delegate some article or example.
Check if fname isn't nil. If you forgot to properly connect it in Interface Builder, fname will be nil and all messages sent to it (like setText:) will be ignored.
Please First check that you have bind your textfield with your fname variable. If yes then try to assign value using this:
fname.text=[NSString stringWithFormat:#"%#",firstName];
Just try this. I hope this will work for you.
Get your first name(i.e value from json) into global value and assign that global value into your textfield . It is so simple. if you still have doubts than reply i'll post sample code
txtName.text=firstname; OR
txtName.text=[NSString stringWithFormat:#"%#",firstName];
Using Delegate i solved this problems
In my contactViewController.m file:
-(IBAction)list:(id)sender{
vedant=[[WebserviceViewController alloc]init];
vedant.delegate=self;
[vedant listContacts];
}
In webserviceViewController.h I created my own delegate
#protocol WebservicesDelegate <NSObject>
-(void)allContacts:(NSString *)JSONResponse;
#end
then in webserviceViewController.m file after getting the json response from backend i am sending the response back to my contactViewController.m file using this code
[self.delegate allContacts:jsonResponse];
the compiler comes back to allContacts function in contactViewController.m file this code is same i didn't change the code now it prints the value.
-(void)allContacts:(NSString *)JSONResponse{
NSLog(#"%#",JSONResponse);
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
int accCount =[json count];
for(int i=0;i<accCount;i++){
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
// NSLog(#"%#",JSONResponse);
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
NSString *firstName = [NSString stringWithFormat:#"%#", [[json objectAtIndex:i] objectForKey:#"first_name"]];
NSLog(#"%#",firstName); //this prints the actual first name in console But
fname.text=firstName;
NSLog(#"%#",fname.text); //it prints "(Null)" in console
}
}
I think because i was trying to get data from different view and wanted to display the data in another view was the problem.
But by creating the delegate the problem was solves and i can easily send the data from one view to another view.

How to Parse this JSON in Objective-C

I'm new in iPhone programming.
I have to parse this data in JSON in Objective-C.
{"success":1,"check":[{"ChkKey":"2","ChkDeb":"Connection 1","ChkSSID":"Netgear-1111","ChkIP":"192.168.2.103","ChkBlk":"0"}]}
I follow the example for parsing data with Json. But this JSON is so different.
It is composed by two Array.
How can i proceed?
Thanks - A.b.
How about trying something like this ...
//JSON string
NSString *jsonString = #"{\"success\":1,\"check\":[{\"ChkKey\":\"2\",\"ChkDeb\":\"Connection 1\",\"ChkSSID\":\"Netgear-1111\",\"ChkIP\":\"192.168.2.103\",\"ChkBlk\":\"0\"}]}";
//Parse JSON string into an NSDictionary
NSError *e = [[NSError alloc] init];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];
//Output the value of success
NSLog(#"Success:%#", [jsonData objectForKey:#"success"]);
//Get data in the check array
NSDictionary *checkData = [[jsonData objectForKey:#"check"] objectAtIndex:0];
//Output the value of ChkSSID
NSLog(#"ChkSSID:%#", [checkData objectForKey:#"ChkSSID"]);

Converting an NSArray of Dictionaries to JSON array in iOS

I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray that I have to pass.
array([0] => array('latitude'=>'10.010490',
'longitude'=>'76.360779',
'altitude'=>'30.833334',
'timestamp'=>'11:17:23',
'speed'=>'0.00',
'distance'=>'0.00');
[1] => array('latitude'=>'10.010688',
'longitude'=>'76.361378',
'altitude'=>'28.546305',
'timestamp'=>'11:19:26',
'speed'=>'1.614',
'distance'=>'198.525711')
)`
and the required format is like this
[
{ "latitude":"10.010490",
"longitude":"76.360779",
"altitude":"30.833334",
"timestamp":"11:17:23",
"speed":"0.00",
"distance":"0.00"
},
{
"latitude":"10.010688",
"longitude":"76.361378",
"altitude":"28.546305",
"timestamp":"11:19:26",
"speed":"1.614",
"distance":"198.525711"
}
]
Any one have solution? Thanks in advance.
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstJsonDictionary];
[arr addObject:secondJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
The simplest and best approach !!!
To convert NSArray or NSMutableArray into jsonString you can first convert it into NSData and then further convert that into a NSString. Use this code
NSData* data = [ NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil ];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It helped me and hope it helps you as well. All the best.
I would recommend the SBJson-Framework.
Converting an NSMutableArray is as simple as NSString *jsonString = [yourArray JSONRepresentation];
Edit: Jack Farnandish is right u have to transform it into a NSDictionary before you can convert it to Json. In my example the NSMutableArray has to contain the Dictionary. The Array is only needed to create the square brackets at the beginning and the end of the string.
You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON
First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.
#import <JSONKit/JSON.h>
NSArray *array = // Your array here.
NSString *json = [array JSONString];
NSLog(#"%#", json);
JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.
Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).
Is the service you are calling a RESTful service?
If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.

Parsing JSON to get Google Reader Label information

I am trying to make a google reader app. I am able to get the subscription list in JSON format like this:
{"subscriptions":[{"id":"feed/http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss","title":"ActiveState Code: Python recipes","categories":[{"id":"user/014533032765194560dwd0/label/Programming","label":"Programming"}],"sortid":"E6312EFB","firstitemmsec":"1258141669516","htmlUrl":"http://code.activestate.com/recipes/langs/python/"},
I am interested in getting the label value (in the above case "Programming") into an array. Here is my current code:
-(BOOL)parsedSuccess {
SBJsonParser *parser = [[SBJsonParser alloc]init];
if (!receivedData) {
[self getSubscriptionList:GOOGLE_READER_SUBSCRIPTION_LIST];
}
NSMutableString *body = [[NSMutableString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:#"subscriptions"];
NSString *subTitles;
for (NSDictionary *title in subs){
subTitles = [title objectForKey:#"categories"];
NSLog(#"%#",subTitles);
}
}
return YES;
}
Can someone help me in getting the label values?
[[[[[result valueforkey:#"subscription"]objectatindex:0]valueforkey:#"categories"]objectatindex:intvalue]valueforkey:#"label"];
I just helped to make logic. Be sure to check for spelling mistakes before implementing.