How to parse api response on table view? - iphone

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];

Related

How to separate JSON response in iphone

I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);
for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.
It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);
You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];
Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file
Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS

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"]);

JSONKit: changing and serializing JSON attribute's value

I am using JSONKit to parse JSON string into NSDictionary:
NSDictionary *deserializedData = [jsonString objectFromJSONString];
My question is: how can I change the dictionary values and get a changed JSON String?
I've tried to change the dictionary values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
But the app crashes in that line. What am I doing wrong?
Thanks in advance!
While the other answers are correct, what you really want in this case is:
NSMutableDictionary *deserializedData = [jsonString mutableObjectFromJSONString];
The mutableObjectFromJSONString method will create a mutable dictionary directly, which saves time and memory.
NSDictionary is an immutable dictionary, you need NSMutableDictionary to change the data. I'm not sure about JSONKit, but the built-in Cocoa JSON parser has a flag to return the data in mutable containers.
In worst case, you can do something like that:
NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:[jsonString objectFromJSONString]];
[data setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
//
// we begin with our string in json format
//
NSString *jsonString = [[NSString alloc] initWithString:#"{\"1\":\"Hole 1: Rossy Robinson - $25\",\"2\":\"Hole 7: Davey Ambrose - $25\",\"3\":\"Hole 14: Ross Robinson - $25\"}"];
//
// convert the json string to an NSMutableDictionary
//
NSError *e;
NSMutableDictionary *JSONdic = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
//
// change a value and add a new value in the dict
//
NSLog(#"before: object for key 1 is: %#", [JSONdic objectForKey:#"1"]);
[JSONdic setObject:#"xxx" forKey:#"1"];
[JSONdic setObject:#"Phil McQuitty" forKey:#"2"];
//
//convert dictionary object to json data
//
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&e];
//
// convert the json data back to a string
//
NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\
//
// print out the final results
//
NSLog(#"back to string: %#", jsonText);
You try to change an immutableobject.
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];
This is a mutable dictionary and you can change the values in it.
You try like this:
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];
and then change the values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
For NSDictionary we cannot add or change values, thats why application is crashing.

how to parse array of objects using json for 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.