Strange output when importing JSON to Objective-C - ios

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

Related

JSON Parsing: NSArray POST

How to POST NSArray values in JSON or Is there any possible to POST JSON values.
I thing this is useful, otherwise I modify something in code
NSMutableArray * arr = [[NSMutableArray alloc] init];
// assume that this is your Array
[arr addObject:#"1"];
[arr addObject:#"2"];
// convert the NSArray to NSdata , the reason is always the web service get string only
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
// finally append the -- jsonString to your web service

How to get the values from json service [duplicate]

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

How to convert NSArray of NSStrings into Json String iOS

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

How to convert NSDictionary to NSString which contains json of NSDictionary?

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.

JSON parser returns Null

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.

Resources