Assign single line json element to label in Objective-c - objective-c

I'm trying to assign a simple json feed element to a label.
My json feed that looks like this:
[{"code":501,"data":{"req":"0"}}]
My code after I've retrieved it from a url:
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
NSArray* json_object = [NSJSONSerialization
JSONObjectWithData:POSTReply
options:0
error:nil];
NSArray *json_object_line = [json_object objectAtIndex:0];
mainLabel.Text= [json_object_line valueForKey:#"code"];
There is no way I can get this to work. The app simply crashes unless I remove the last 2 lines. I've tried a lot of other options (especially for the last 2 lines) to no avail.
Is there anything I'm doing wrong?

You tried to assign NSNumber to the label's text property. It's a reason of the crash. The proper way is to get a formatted string from JSON field:
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:POSTReply.bytes
length:POSTReply.length
encoding:NSASCIIStringEncoding];
NSArray* json_object = [NSJSONSerialization JSONObjectWithData:POSTReply
options:0
error:nil];
NSDictionary *json_object_line = json_object[0];
mainLabel.text= [NSString stringWithFormat:#"%#", json_object_line[#"code"]];

Related

Am stuck in parsing Push Notifications

I want to fetch value of description from the below response. In body few more key-value pairs are there. I have tried, unfortunately am failing to crack. My code is in Objective C.
And My code for Parsing as below
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notification.request.content.userInfo options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"After Validation JSON VALUE IS : %#", jsonString);
NSData *BodyData = [NSJSONSerialization dataWithJSONObject:[[[notification.request.content.userInfo objectForKey:#"aps"] objectForKey:#"alert"] objectForKey:#"body"] options:0 error:NULL];
NSString *BodyString = [[NSString alloc] initWithData:BodyData encoding:NSUTF8StringEncoding];
NSLog(#"After Validation JSON VALUE IS : %#", BodyString);
Here is my complete response. I want to fetch all the values from body section.
{
"aps":{
"alert":{
"title":"Your bill is ready from shop My Store",
"body":"{\"shop_id\":\"16\",\"shop_name\":\"My Store\",\"description\":\"Thank you for Shopping\",\"notification_type\":\"bill\",\"shop_category\":\"entertainment\",\"bill_date\":\"2018-01-13\",\"bill_url\":\"dXBsb2FkLzRvcmVfMDExMzIwMTgtMTY0NjI5LnBkZg==\",\"approve\":1}"
},
"sound":"1"
},
"gcm.message_id":"0:1515842219916508%a1c76c71a1c76c71",
"gcm.notification.vibrate":"1"
}
convert your body string to json
NSString*bodyKeyValue = #"{\"shop_id\":\"16\",\"shop_name\":\"My Store\",\"description\":\"Thank you for Shopping\",\"notification_type\":\"bill\",\"shop_category\":\"entertainment\",\"bill_date\":\"2018-01-13\",\"bill_url\":\"dXBsb2FkLzRvcmVfMDExMzIwMTgtMTY0NjI5LnBkZg==\",\"approve\":1}"; //[[[notification.request.content.userInfo objectForKey:#"aps"] objectForKey:#"alert"] objectForKey:#"body"];
NSData *data = [bodyKeyValue dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonOutput = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",jsonOutput);
NSLog(#"approve Key value:%#",[jsonOutput objectForKey:#"approve"]);

I tried to download this geocode data

Basically I am accessing this URL
http://maps.googleapis.com/maps/api/geocode/json?address=sudirman&sensor=true&bounds=-7.186696,105.7727|-5.186696,107.7727
However, the result is empty. Even though it should show something. I used objective-c
With this code:
response= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error:&error];
json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
I think the | need to be urlencoded. How to do so?
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error:&error];
returns NSData, which when serialised will produce JSON, so you need to do:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
to get the JSON.

Send json string as httpBody data using objective c

I have been trying to send json string converted to nsdata to http body part.
but i always find that correct value is never passed on to
What i want on server :
{"request":"{\"Files\":[{'FileName':'11111111','FileType':'test'}]}"}
What i receive on server :
{"request":{"Files":[{"FileName":"test.html","FileType":"test"}]}}
Can anybody suggest me what am i doing wrong :
I tried following ways :
Way : 1
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict1 options:0 error:nil];
NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
Way : 2
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict1 options:0 error:nil];
[request setHTTPBody:jsonData];
Crust is i want to send nsdata format of json tring but i cant get perfect value on the server.
Can anybody suggest me a possible way to achieve this?
Try this one.
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:requestDict1 options:NSJSONWritingPrettyPrinted error:nil];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:jsonString];

NSJSONSerialization: treating special characters properly

I want to use online data from a JSON file. It's currently working, but when I use special characters it shows "null". Here's the code I'm using:
NSString *urlString = [NSString stringWithFormat:#"http://belesios.com/burc/koc2.php"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", json);
NSString *ciktiText = [[NSString alloc] initWithFormat:#"%#", json];
[kocLabel setText:ciktiText];
For example, if my file contains ç or ü, null is returned. What do I need to do?
Try this method to find out what encoding is used when data is pulled from server:
NSStringEncoding encoding;
NSString *jsonString =[NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
if (error)
NSLog(#"Error: %#", error);
You should check encoding of data returned by the server. Your code is correct but you should add some check if error != nil then don't execute and display or log that.
NSString *jsonString = #"{\"abc\":\"ç or ü\"}";
NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Output: %#", jsonObj);
Output: { abc = "\U00e7 or \U00fc"; } This is how your server response should look like with encoded char if you use Fiddler or some other software to print raw response.
Currently your data looks like where as UTF8 encoded chars should be like \U00e7 = ç

How do i get the modhash and cookie from logging into reddit with the api?

NSString *username = #"username";
NSString *password = #"password";
NSURL *loginurl = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.reddit.com/api/login/%#",username]];
NSMutableURLRequest *loginrequest = [NSMutableURLRequest requestWithURL:loginurl];
[loginrequest setHTTPMethod:#"POST"];
NSData *loginRequestBody = [[NSString stringWithFormat:#"api_type=json&user=%#&passwd=%#",username,password] dataUsingEncoding:NSUTF8StringEncoding];
[loginrequest setHTTPBody:loginRequestBody];
NSURLResponse *loginResponse = NULL;
NSError *loginRequestError = NULL;
NSData *loginResponseData = [NSURLConnection sendSynchronousRequest:loginrequest returningResponse:&loginResponse error:&loginRequestError];
NSString *loginResponseString = [[NSString alloc]initWithData:loginResponseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginResponseString);
the NSLog prints this: (with some letters replaced)
{"json": {"errors": [], "data": {"modhash":
"j5hq16ukw2f17a9c153xxxxxxxxxa72ad989c96c904d49a97e", "cookie":
"13986184,2012-07-14T12:41:05,349f968b3089af75978xxxxxxxxxxxx761397ba0"}}}
How do i access the modhash and the cookie? I tried
[loginResponseData valueForKey:#"json"];
but it says that the class is not key value coding-compliant for the key json
loginResponseString is an NSString -- it doesn't know if it has JSON inside. You have to parse this JSON to an NSDictionary then you can use its methods to retrieve response data. Try my JSON parser: http://github.com/H2CO3/CarbonateJSON
Example using my CarbonateJSON library:
NSDictionary *parsedResponse = [loginResponseString parseJson];
NSString *modhash = [[[parsedResponse objectForKey:#"json"] objectForKey:#"data"] objectForKey:#"modhash"];
For anyone looking at this after me, you can check out H2CO3's solution, but I found that the easiest solution was using NSJSONSerialization to do it in a supported fashion.
NSError *error;
NSData *jsonData = [loginResponseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *loginResults = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSString *modhash = [[[loginResults valueForKey:#"json"] valueForKey:#"data"]valueForKey:#"modhash"];
worked for me.