I am using iOS 5 new feature to parse JSON and I have no idea that why I am not getting any key value pairs. "aStr" (string representation of data) is putting the right JSON on the output window but I am getting nothing in "dicData" and there is no error either.
Any help is greatly appreciated.
This is what I am using
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.macscandal.com/?json=get_post&post_id=436"]];
NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//NSLog(#"data = %#",aStr);
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
//NSLog(#"error = %#",error);
NSString *title = [dicData objectForKey:#"title"];
Your JSON is formatted this way:
{
"status": "ok",
"post": {
"id": 436,
"type": "post",
"slug": "foxconn-likely-to-get-assembly-contract-for-apple-tv-set",
"url": "http:\/\/www.macscandal.com\/index.php\/2011\/12\/28\/foxconn-likely-to-get-assembly-contract-for-apple-tv-set\/",
"status": "publish",
"title": "Foxconn Likely to get Assembly Contract for Apple TV Set",
...
I haven't used NSJSONSerialization but just following the natural JSON parsing alg this is how I would try to get it.
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSDictionary *postData = [dicData objectForKey:#"post"];
NSString *title = [postData objectForKey:#"title"];
EDIT
Just a simple check method:
-(void)check{
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.macscandal.com/?json=get_post&post_id=436"]];
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSDictionary *postData = [dicData objectForKey:#"post"];
NSString *title = [postData objectForKey:#"title"];
NSLog(#"%#", title);
}
Related
How do I extract just the "token" value from the following code? I'm looking to save this value into a string.
Is meta an array? If so how would I extract the data from the "token" value?
thanks for any help
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Response ==> {"meta":[],"data":{"token":"IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU="}}
2013-07-19 15:10:23.139 appName [11190:907] {
data = {
token = "IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU=";
};
meta = (
);
}
I believe the data is in JSON format. In that case, this should work.
NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
I'd just do this:
NSData *responseData = [NSData dataWithContentsOfURL:yourURL];
NSString *token = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:NULL][#"data"][#"token"];
It will be nil if there's any error.
In your Case, meta is an Array and data is a Dictionary. If your Response is properly formatted in JSON then you can use the below sample code to get the TokenString and metaArray.
Sample Code :
NSData *data = [NSData dataWithContentsOfURL:yourURL];
NSError* error = nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
NSArray *meta = [responseDict objectForKey:#"meta"];
NSLog(#"\ntoken :: %#\nmeta :: %#",token,meta);
PS : To know more about JSON response , take a look at this Answer.
How can I get formatted address like Covington, AL, USA of google web service in my iphone
from the below url
http://maps.google.com/maps/api/geocode/xml?latlng=31.319016,-86.399871&sensor=false
- (void) getAddress
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://maps.google.com/maps/api/geocode/json?latlng=31.319016,-86.399871&sensor=false"]];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSString *str = [[[dict objectForKey:#"results"] objectAtIndex:0] valueForKey:#"formatted_address"];
NSLog(#"Address = %#", str);
}
Use this json this is much faster that xml.
How to create json Object with NSData in Objective C. I'm having values in a NSData variable.
You can use it like this in iOS 5 (if you are sure of your json structure you can directly use NSArray or NSDictionary doing a cast)
NSError *jsonError;
id jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:myData options:NULL error:&jsonError];
if(jsonError) {
// check the error description
NSLog(#"json error : %#", [jsonError localizedDescription]);
} else {
// use the jsonDictionaryOrArray
}
if you have a value in NSData object then you can convert it in NSString variable like bellow
NSString *response = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
Edited...
i am not sure what you want but i give you the json array from string like bellow..
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *arrData = [json objectWithString:responseString error:&error];
[responseString release];
you can get data in array
hope this help you mate...
:)
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"youur link"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
if([jsonObjects isKindOfClass:[NSArray class]]){
//Is array
}else if([jsonObjects isKindOfClass:[NSDictionary class]]){
//is dictionary
}else{
//is something else
}
EDIT FOR SWIFT
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] {
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
I am trying to parse Json response from This URL. I have used SBJsonParser, MTJSON and another parser but i am getting NULL in all three case.
apiUrlStr = #"http://maps.google.com/maps?output=dragdir&saddr=Delhi&daddr=Mumbai+to:hyderabad";
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
SBJsonParser *json = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *dictionary = [json objectWithString:apiResponse];
NSLog(#"dictionary=%#", [json objectWithString:apiResponse]);
2011-12-09 16:59:01.226 MapWithRoutes[2523:207] dictionary=(null)
Plz suggest me something
Oke if checked the url you gave with JSONlint.com and the JSON is not valid. thus can not be parsed by any library.
If you used JSONkit you can supply a NSError object with the parse call to see what went wrong:
NSError *error = nil;
NSDictionary *dictionary = [apiResponse objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
if (!dictionary) {
NSLog(#"Error: %#", error);
}
I am trying to use TouchJSON and here is what I have done to test it :
NSString *jsonString = #"{\"firtname\": \"Matthieu\",\"lastname\": \"Ravey\",\"age\": 22}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSString *firstname = [dictionary objectForKey:#"firstname"];
NSLog(#"%#", firstname);
But it logs null instead of Matthieu, what am I missing ?
Thanks
In your json string - NSString *jsonString = #"{\"firtname\": \"Matthieu\",\"lastname\": \"Ravey\",\"age\": 22}"; it says firtstring.
Try accessing this dictionary with same keys !
So the change would be -
NSString *firstname = [dictionary objectForKey:#"firtname"];