Get JSON URL From String in Objective C - objective-c

I just try to deploy client server apps in Objective-C. I get an json string like this from server when I make a query:
#"{"url":"http://my-company.com/json"}".
How do I extract the http://my-company.com/json directly using Objective C?

Read more about NSJSONSerialization
NSString *jsonString = #"{\"url\":\"http://my-company.com/json\"}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSString *url = [jsonDict objectForKey:#"url"];
NSLog(#"url: %#", url);

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

iOS to parse JSON?

I am getting the following response from server
[{"id":"16","name":"Bob","age":"37"},{"id":"17","name":"rob","age":"28"}];
I am using AFNetworking framework for it,
I am getting the above response in NSData and then using the the below code, I am able to collect the data in NSDictionary
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
But how to parse the "name" and "age" value from that NSDictionary?
You expected NSDictionary but your response gives you array of dictionaries, try this:
NSArray *array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
for (NSDictionary *dict in array)
{
NSLog(#"Name: %#, age: %#", dict[#"name"], dict[#"age"]);
}
//Extended
From the comment below it looks like you have a string from the response, not NSArray as you show in the code above.
You can parse string to get the data you want or you can convert it back to the json and NSArray:
NSString * jsonString = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//As I post above
Now you should have an NSArray and my code should do the job.

App crashing because NSArray objectforkey: Objective C

I am trying to parse some Json with Objective C.
My problem is that I am getting the correct json back but when I try parse some of the json my app crashes.
// i will use a code from connect to DB tutorial
NSString *strURL = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Asset/AssetsWithSerial?Serial=S00000001"];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",strResult);
NSError *error;
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"AssetDesc"]; //2
NSLog(#"value: %#", defineJsonData); //3
Here is my json:
[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]
I am trying to get the AssestName out of the string. I must be doing something wrong.
The whole thing is an array containing a dictionary, not a dictionary containing an array...
This is a very dirty way to get the value you want - you want to write something more safe than this. Try checking the type of class returned before you try to use it...
NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSDictionary* defineJsonData = [json lastObject]; //2
NSLog(#"value: %#", [defineJsonData objectForKey:#"AssetDesc"]); //3

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 = ç

Parsing special characters in JSON

I'm now parsing with NSJSONSerialization
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"url"]];
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
[self setTableData:jsonDictionary];
But it won't parse my JSON because of special characters in the JSON like the letter 'ü' when i remove the 'ü' from the JSON it's working correclty. I tried the code above and:
options:utf8...
Does anyone know how i can fix this?
Try using NSString with which you can explicitly specify encoding. Ex:
NSString *string = [NSString stringWithContentsOfURL:webURL encoding:NSUTF8StringEncoding error:&error];
You can then convert the NSString object to NSData and then do the JSON serialisation..
Try to change NSJSONReadingMutableContainers with NSJSONReadingMutableLeaves. This solved me similar problem.