iOS parse specific jSON - ios

I meet a problem to parse a jSON, I've a jSON like that :
{
"id": 0,
"message": "ok"
}
I tried several things to try to get the value of "id", and "message", but I've always an error..
How can I do to pick the value of "id", and "message" please ?
(I get the result of my JSON in a NSMutableArray)
EDIT :
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSMutableDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:publicTimeline.allKeys];
[sortedArray sortUsingSelector:#selector(localizedStandardCompare:)];
return sortedArray;

Your JSON string represents a dictionary. So you have to use NSDictionary instead of NSArray.
EDIT I
// convert dictionary into JSON
NSDictionary *fromDict = #{#"id": #(0), #"message": #"ok"};
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:fromDict options:0 error:nil];
// convert data (like you get from an API request) to dictionary
NSDictionary *toDict = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];

Try this,
Parse the JSON response to NSDictionary
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *message = [responseDictionary valueForKey:#"message"];

I think its helpful to you (In this response you get first dictionary and dictionary contains two key.so )
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSString *message = [publicTimeline valueForKey:#"message"];
I Think it useful link for you. json parser

Related

Xcode NSData to Json returns null

NSData *urlDatat = [NSData dataWithContentsOfURL: [NSURL URLWithString:stringURL]];
NSDictionary* json1 = [NSJSONSerialization JSONObjectWithData:urlDatat options:0 error:&error];
NSString *urlDataString =[[NSString alloc] initWithData:urlDatat encoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlDatat options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments|NSJSONReadingMutableLeaves error:&error];
Both json1 and json return null. Actual JSON data from the server is ={"statusCode":"1","message":"success","utcMilliSeconds":"1501953923847"}
try to use
NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:urlDatat options:NSJSONReadingMutableLeaves error:&error];
UPDATED
NSURL *url = [NSURL URLWithString:#"https://api.kidstriangle.com/KTStandaloneAPI/Common/GetUtcMilliSeconds"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

How to parse the data into Json Format in ios?

I Converted NSData to string then I am getting the string like below, Now I want to parse this one. If parse with json serilazation I am getting json data nil.
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><EmployeesLoginMethodResponse xmlns="http://tempuri.org/"><EmployeesLoginMethodResult>[{"sms":"You have logged in successfully!","userId":"29","type":"1","name":"mng 56 78"}]</EmployeesLoginMethodResult></EmployeesLoginMethodResponse></soap:Body></soap:Envelope>
If I parse using XML I am Getting The String Like below,In this How to get value of sms,userId,name
[{
"sms": "You have logged in successfully!",
"userId": "13",
"type": "1",
"name": "Suhashini Kumari Singh"
}]
Here is my code
NSString *urlString=[NSString stringWithFormat:#"http://workforce.wifisocial.in/WebServicesMethods/EmployeesWebService.asmx"];
NSString* webStringURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString* requestBody =[NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><EmployeesLoginMethod xmlns=\"http://tempuri.org/\"><username>\%#</username><password>\%#</password><IpAddress>\%#</IpAddress><deviceName>\%#</deviceName></EmployeesLoginMethod></soap:Body></soap:Envelope>",self.userNameTextFiled.text,self.passwordTextField.text,ipAddress,deviceName];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[request setValue:#"\"http://tempuri.org/EmployeesLoginMethod\"" forHTTPHeaderField:#"SOAPAction"];
[request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]] ;
NSError *error;
NSHTTPURLResponse *response = nil;
NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
NSString* responseString = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"%#",responseString);
if (urlData)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
Please try XMLDictionary library. For more reference https://github.com/nicklockwood/XMLDictionary
Just convert your NSData to NSDictionary using XMLDictionary as below
NSDictionary *xmlDictionary = [NSDictionary dictionaryWithXMLData:returnData];
If you got you response in json string then try like below,
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
here responseString is final output json string that you have posted in question.
Then fetch data from json dictionary.
If this scenario will not work then take a look at NSXMLParser, you can refer Appcoda's tutorial.
It's nil because it's not the JSON parsing that's failing but because of the conditional type cast of the resulting object as a dictionary.
It's an array with one item which is dictionary. So, during parsing cast it as a NSArray.
Like,
Instead of:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
Use:
NSArray *arrJson=[NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSDictionary *json = [arrJson objectAtIndex:0];
NSString *sms=[json valueForKey:#"sms"];
NSString *userId=[json valueForKey:#"userId"];
NSString *type=[json valueForKey:#"type"];
NSString *name=[json valueForKey:#"name"];
You can use XML to JSON converter (XMLReader)
: https://github.com/amarcadet/XMLReader
#import "XMLReader.h"
Here is the sample snippet for your code :
NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (urlData)
{
NSDictionary *dict = [XMLReader dictionaryForXMLData:urlData error:&error];
NSLog(#"-----%#-----",dict);
NSError *jsonError;
NSString *json2 = [[[[[[dict valueForKey:#"soap:Envelope"] valueForKey:#"soap:Body"] valueForKey:#"EmployeesLoginMethodResponse"] valueForKey:#"EmployeesLoginMethodResult"] valueForKey:#"text"] stringByReplacingOccurrencesOfString:#"\"" withString:#"\""];
NSData *objectData1 = [json2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:objectData1 options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"-----%#-----",json1);
}

find cell tower location in iOS

Now I m trying to find the tower location using cellID, MNC,MCC and LAC.
If you have the cellId, MNC,MCC and LAC then you can easily find the cell tower location in iOS. after some struggle i get the ans of this problem.
now this is the ans of this question.
#define google_geo_location #"https://www.googleapis.com/geolocation/v1/geolocate?key="
google API LOCATION
NSString * urlString = [NSString stringWithFormat:#"google API key ",google_geo_location];
Create JSON STRING
NSString *json=[NSString stringWithFormat:#"[{\"homeMobileCountryCode\": \"%#\",\"homeMobileNetworkCode\": \"%#\",\"cellTowers\": [{\"cellId\": \"%#\",\"locationAreaCode\": \"%#\",\"mobileCountryCode\": \"%#\",\"mobileNetworkCode\": \"%#\" }]}]",_mcctext,_mnctext,_cellidtext,_lactext,_mcctext,_mnctext];
convert JSON STRING in to JSON DICTIONARY
NSError *jsonError;
NSData *objectData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsondic = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
Create url from string
NSURL *urlStr=[NSURL URLWithString:urlString];
if (urlStr == nil)
{urlStr = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:urlStr];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
set request body, If method type is "POST" use only POST
NSData *data=[NSJSONSerialization dataWithJSONObject:jsondic options:NSUTF8StringEncoding error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString.....%#",jsonString);
NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
// for set requestBody
[request setHTTPBody:requestBody];
now you get response from server
NSHTTPURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSMutableDictionary *resultantDict;
if (responseData != nil)
{
resultantDict=[NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(#"resultantDict=%#",resultantDict);
NSString *errorCode=#"";
NSString *errorMessage=#"";
if ([[resultantDict allKeys] containsObject:#"error"])
{
errorCode=[NSString stringWithFormat:#"%#", [[resultantDict valueForKey:#"error"]valueForKey:#"code"]];
errorMessage= [[resultantDict valueForKey:#"error"]valueForKey:#"message"];
}
}

How can we add video to a tableview?

In my app i want to display a video in subsequent rows of a tableview. Video's are to be fetched from a JSON service which is coming in a string format. How can we achieve this. Any help will be appreciated.
If you want to use GET for getting response(VIDEO) from server just you can try in following method
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[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.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
//If it is Dictionary
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error: &err];
or
//If it is Array
NSMutableArray *json=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSMutableArray *imgvd=[[NSMutableArray alloc]init];
for (int i =0 ; i<json.count; i++)
{
NSString *dd =[[json objectAtIndex:i]objectForKey:#"url"];
NSString *pp = [[json objectAtIndex:i]objectForKey:#"title"];
vedios *myvd = [[vedios alloc]initWithvideo:dd andtitle:pp];
[imgvd addObject:myvd];
}

NSJSONSerialization JSON parsing issue

I have a problem with parsing JSON.
Here's my code:
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/lookup?bundleId=com.clickgamer.AngryBirds"]; //This URL only for testing
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *jsonParsingError = nil;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data = %# ", [[jsonArray objectForKey:#"results"] valueForKey:#"version"]);
}];
In Console it prints out: Data = (
"3.4.1"
)
But I want to have: Data = 3.4.1 What am I doing wrong?
seems valueForKey:#"version" returns an array with only one element.
try this:
NSLog(#"Data = %# ", [[[jsonArray objectForKey:#"results"]
valueForKey:#"version"]
objectAtIndex:0]);
try this:
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
If you try curl http://itunes.apple.com/lookup?bundleId=com.clickgamer.AngryBirds on the command line you can see from the output that the "results" object is an array so when you invoke the valueForKey method on the results array you get an array of all the #"version" keys in that array.
Example:
NSDictionary *test = #{#"results": #[#{#"version":#"1.0"}, #{#"version":#"2.0"}]};
NSLog(#"output: %#", [[test objectForKey:#"results"] valueForKey:#"version"]);
Output:
output: (
"1.0",
"2.0"
)
What you have to do is get the first object in the "results" array and get the version object from that eg.:
test[#"results"][0][#"version"]

Resources