I am trying to learn how to parse JSON data so I can handle big databases. I wrote code to login into a website.
I have following JSON data from a successful login request:
JSON string : correct username and password [{"user_id":"7","first_name":"dada","last_name":"Kara","e_mail":"yaka#gmail","fullname":"Dada Kara","forum_username":"ycan"}]
and i use following code to parse but it doesnt parse it
-(IBAction)loginButton:(id)sender{
NSString *username = usernameTextfield.text;
NSString *password = passwordTextfield.text;
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:kPostUrl]];
[request setHTTPMethod:#"POST"];
NSString *post =[[NSString alloc] initWithFormat:#"e_mail=%#&password=%#", username, password];
[request setHTTPBody:[post dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseStr = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"Response : %#", responseStr);
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"JSON string : %#", json_string);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *responseObj = [parser objectWithString:json_string error:nil];
NSArray *name = [responseObj objectForKey:#"first_name"];
NSLog(#"Name : %#", name);
}
The result from my NSLog for name is NULL
Where is the problem and how can I parse such a data so when it comes to lots of rows I can save it to the local FMDB database on iphone
------------------------------EDIT---------------------------------------------------------------
Actual problem was response JSON string from server included echo beginning of the string,json parser only parses between double quotes "", so all i just needed to trim echo from string and parse new string.
and bingo!
//trim in coming echo
NSString *newString1 = [json_string stringByReplacingOccurrencesOfString:#"correct username and password\n" withString:#""];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:newString1 error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *userID = [dataDict objectForKey:#"user_id"];
NSLog(#"user_id: %#", userID);
output : user_id : 7
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *responseObj = [parser objectWithString:json_string error:nil];
NSDictionary *dataDict = [responseObj objectAtIndex:0];
NSString *name = [dataDict objectForKey:#"first_name"];
Did you print recieve data ? is it showing recieve data from server ? If yes then try with different encoding.
You can use a tool like Objectify ($15 US) or JSON Accelerator ($0.99 US) in the Mac App store to automatically generate data models for you that would make the model as simple as doing object.firstName.
Related
I'm trying to learn JSON with IOS since I'm a beginner in IOS devices, i tried this code so far
-(void)retriveData
{
NSURL *url = [NSURL URLWithString:#"http://localhost/testjson.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cities = [[NSMutableArray alloc] init];
for (int i=0; i<json.count; i++) {
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"CityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"CityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"CityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"Country"];
Country *myCity = [[Country alloc] initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry];
[cities addObject:myCity];
}
}
Anyone can show me now how i can print the data? this is the json file
[{"0":"1","id":"1","1":"Muscat","CityName":"Muscat","2":"Muscat","CityState":"Muscat","3":"25000","CityPopulation":"25000","4":"Oman","Country":"Oman"},{"0":"2","id":"2","1":"Bawsher","CityName":"Bawsher","2":"Muscat","CityState":"Muscat","3":"10000","CityPopulation":"10000","4":"Oman","Country":"Oman"},{"0":"3","id":"3","1":"AlMawalih","CityName":"AlMawalih","2":"Seeb","CityState":"Seeb","3":"5000","CityPopulation":"5000","4":"Oman","Country":"Oman"},{"0":"4","id":"4","1":"Oran","CityName":"Oran","2":"Oran","CityState":"Oran","3":"100000","CityPopulation":"100000","4":"Algeria","Country":"Algeria"},{"0":"5","id":"5","1":"Constantine","CityName":"Constantine","2":"Constantine","CityState":"Constantine","3":"150000","CityPopulation":"150000","4":"Algeria","Country":"Algeria"}]
Below is my very understandable and basic coding according to your question.It is helpful for you.
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/testjson.php"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"The json output array is - %#",jsonArray);
for(int i=0;i>[jsonArray count];i++)
{
NSString *strZero = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"0"]];
NSLog(#"The zero is-%#",strZero);
NSString *strOne = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"1"]];
NSLog(#"The One is-%#",strOne);
NSString *strTwo = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"2"]];
NSLog(#"The Two is-%#",strTwo);
NSString *strThree = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"3"]];
NSLog(#"The three is-%#",strThree);
NSString *strFour = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"4"]];
NSLog(#"The four is-%#",strFour);
NSString *strID = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"id"]];
NSLog(#"The ID is-%#",strID);
NSString *strCityName = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityName"]];
NSLog(#"The CityName is-%#",strCityName);
NSString *strCityState = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityState"]];
NSLog(#"The CityState is-%#",strCityState);
NSString *strCityPopulation = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityPopulation"]];
NSLog(#"The CityPopulation is-%#",strCityPopulation);
NSString *strCountry = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"Country"]];
NSLog(#"The Country is-%#",strCountry);
}
By printing you mean show the data in the console ?
Did you try this ?
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#", str);
This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details
I have an Array of Roll Numbers
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
I need to send this array in a Web Service request
whose format is like this (in JSON format)
JSON data
{
"existingRoll":["22","34","45","56"], // Array of roll numbers
"deletedRoll":["20","34","44","56"] // Array of roll numbers
}
but I am facing problem in converting Array of Roll numbers (rollArray) into json String
in the desired format.
I am trying this
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:[rollArray componentsJoinedByString:#","] forKey:#"existingRoll"];
NSString *str = [Self convertToJSONString:postDict]; // converts to json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:0 error:nil];
[request setHTTPBody:jsonData];
I am using iOS 7
There is no need to use the following code snippets:
[rollArray componentsJoinedByString:#","]
NSString *str = [Self convertToJSONString:postDict];
You can create JSON by using the following code:
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:rollArray forKey:#"existingRoll"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSLog(#"%#",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
Try this :
NSDictionary *object = #{
#"existingRoll":#[#"22",#"34",#"45",#"56"],
#"deletedRoll":#[#"20",#"34",#"44",#"56"]
};
if ([NSJSONSerialization isValidJSONObject:object]) {
NSData* data = [ NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil ];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(str);
}
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:#"Login" forKey:#"methodName"];
[postDict setValue:#"admin" forKey:#"username"];
[postDict setValue:#"12345" forKey:#"password"];
[postDict setValue:#"mobile" forKey:#"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
//#"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
You can use following method to get Json string from any type of NSArray :
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:rollArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Json string is: %#", jsonString);
As the question says, I get an unexpected output when importing JSON into a TableView class.
JSON:
{"city":"Cambridge"}{"city":"Oxford"}
Objective-C:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.domain.com/cities.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%#", response);
Output:
<7b226369 7479223a 2243616d 62726964 6765227d 7b226369 7479223a 224f7866 6f726422 7d>
Fairly sure I'm structuring my JSON wrongly...
Your response is of NSData type and needs to be converted to a string.
NSString *responseString = [[NSString alloc] initWithBytes:[response bytes] length:[response length] encoding:NSUTF8StringEncoding];
NSLog(responseString);
You can also use the initWithData as described elsewhere
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
While this is useful for debugging, to actually extract or work with the data, you will want to convert it to dictionary or array.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL];
From here, you can reference items in the dictionary.
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
NSLog(#"%#",responseArray);
NSMutableArray *cityArray =[[NSMutableArray alloc] init];
for (int i=0; i<[responseArray count]; i++)
{
[cityArray addObject:[NSString stringWithFormat:#"%#",[[responseArray objectAtIndex:i] valueForKey:#"city"];
}
Please note that, I believe you would fix that json and make it to json returning an array.
NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
How to convert NSDictionary to NSString which contains JSON of NSDictionary ?
I have tried like but without success
//parameters is NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
if jsonData is NSDictionary
NSString *str=[NSString stringWithFormat:#"json data is %#", jsonData];
OR if jsonData is NSData
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
If you just want to inspect it, you can create a NSString:
NSString *string = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
But if you're writing it to a file or sending it to a server, you can just use your NSData. The above construct is useful for examining the value for debugging purposes.