Invalid touchJSON string - iphone

I get an invalid JSON string, which contains ; ( characters. Any guess what is going on?
My Code:
-(void)getJSONFeed {
// Create the URL & Request
NSURL *feedURL = [NSURL URLWithString:
#"http://maps.googleapis.com/maps/api/geocode/json? address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true"];
NSURLRequest *request = [NSURLRequest requestWithURL:feedURL];
// Example connection only. Add Timeouts, cachingPolicy in production
[NSURLConnection connectionWithRequest:request delegate:self ];
// init the jsonData Property
jsonData = [[NSMutableData data] retain];
}
// NSURLConnection Delegate Methods. You would want to include more for error handling //
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data {
NSLog(#"Recieving Data...");
// Append the incomming data as it is received
[jsonData appendData:data];
NSLog(#"%#",jsonData);
}
-(NSDictionary *)parseJSON:(NSMutableData *)data {
NSLog(#"Parsing JSON");
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
return dictionary;
}
// Parse JSON results with TouchJSON. It converts it into a dictionary.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Fininshed Loading...");
NSDictionary * feedDictionary = [self parseJSON:jsonData];
NSLog(#"JSON as NSDictionary: %#", feedDictionary);
}
{
results = (
{
"address_components" = (
{
"long_name" = 1600;
"short_name" = 1600;
types = (
"street_number"
);
},
{
"long_name" = "Amphitheatre Pkwy";
"short_name" = "Amphitheatre Pkwy";
types = (
route
);
},
{
"long_name" = "Mountain View";
"short_name" = "Mountain View";
types = (
locality,
political
);
},
{
"long_name" = "San Jose";
"short_name" = "San Jose";
types = (
"administrative_area_level_3",
political
);
},
{
"long_name" = "Santa Clara";
"short_name" = "Santa Clara";
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = California;
"short_name" = CA;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
},
{
"long_name" = 94043;
"short_name" = 94043;
types = (
"postal_code"
);
}
);
"formatted_address" = "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA";
geometry = {
location = {
lat = "37.422782";
lng = "-122.085099";
};
"location_type" = ROOFTOP;
viewport = {
northeast = {
lat = "37.4259296";
lng = "-122.0819514";
};
southwest = {
lat = "37.4196344";
lng = "-122.0882466";
};
};
};
types = (
"street_address"
);
}
);
status = OK;
}
UPDATE:
Somehow it interprets it as a Property list. The format seems to be similar to the original NeXTSTEP format with = ;

I'm not 100% sure what the question is. You do a valid HTTP connection, which makes a meaningful request from Google (if you delete the six spaces in the middle that are almost certainly a result of the code copy and paste to here). You accumulate the result. In the given code you appear to leak the object jsonData, but I assume that's irrelevant to the question.
You use the CJSONDeserializer object which I've not heard of but seems to be commonly mentioned on Google so is probably trustworthy. It returns a valid NSDictionary. You print the dictionary and it has the correct results in it.
Is the confusion just that when you print the dictionary to the console, it doesn't look identical to the JSON you received? If so then that's because it no longer has any concept that it came from JSON and Cocoa predates the JSON standard and hence doesn't use it for logging.
In any case, feedDictionary is a valid dictionary. The following:
NSLog(#"%#", [feedDictionary objectForKey:#"status"]);
Would print the string 'OK'. This:
NSArray *addressComponents = [feedDictionary objectForKey:#"address_components"];
for(NSDictionary *component in addressComponents)
{
NSLog(#"%#", [component objectForKey:#"long_name"]);
}
Would print the strings '1600', 'Amphitheatre Pkwy', 'Mountain View', 'San Jose', 'Santa Clara', 'California', 'United States', '94043' in that order.
If you want to print the raw JSON to the console, you probably want something like this (assuming the result comes back as UTF8):
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Fininshed Loading...");
NSString *feedString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON was: %#", feedString);
[feedString release];
/*NSDictionary * feedDictionary = [self parseJSON:jsonData];
NSLog(#"JSON as NSDictionary: %#", feedDictionary); */
}
Though then you'll still need to parse it to a dictionary to get meaningful results from it.

Related

Can we get user zip code using facebook sdk?

I am using facebook sdk 3.0
At facebook i have added users full address as
Address- 1, Infinite loop
city/town - Cupertino, CA
UPDATE
As per the answer I tried to use FBGraphLocation protocol like this
NSDictionary<FBGraphUser> *user
id<FBGraphPlace> objPlace = user.location;
id<FBGraphLocation> objLocation = objPlace.location;
NSLog(#"place.location : %# location.street : %#",objPlace.location,objLocation.street);
It is giving (null) for both. also I am getting objLocation object as (null)
In facebook sdk response, I am getting location as only this
location = {
id = 123456789123456;
name = "Cupertino, California";
}
This is not the enough information from where i can get the zipcode of the use.
If facebook does not allow to provide zip code information then any way to get zipcode from only "Cupertino, California" information ?
I have used this url
http://maps.googleapis.com/maps/api/geocode/json?address=Cupertino,%20California&sensor=true
which give me result as
{
"long_name" = Cupertino;
"short_name" = Cupertino;
types = (
locality,
political
);
},
{
"long_name" = "Santa Clara";
"short_name" = "Santa Clara";
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = California;
"short_name" = CA;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
}
If I statically put that address into the URL as
http://maps.googleapis.com/maps/api/geocode/json?address=1%20Infinite%20Loop,%20Cupertino,%20CA&sensor=true
Then It gives me Zip code also.
{
"long_name" = 1;
"short_name" = 1;
types = (
"street_number"
);
},
{
"long_name" = "Apple Inc.";
"short_name" = "Apple Inc.";
types = (
establishment
);
},
{
"long_name" = "Infinite Loop";
"short_name" = "Infinite Loop";
types = (
route
);
},
{
"long_name" = Cupertino;
"short_name" = Cupertino;
types = (
locality,
political
);
},
{
"long_name" = "Santa Clara";
"short_name" = "Santa Clara";
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = California;
"short_name" = CA;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
},
{
"long_name" = 95014;
"short_name" = 95014;
types = (
"postal_code"
);
}
But from the Facebook sdk, I am only getting the City/Town (as stated above), added in contact Information at Facebook.com
How can I do this?
After digging into the SDK I found out, that you can access a user's zipcode and street using the FBGraphLocation API, which is part of the FBGraph API.
To get a FBGraphLocation you'll acess the location property of a FBGraphUser
/*!
#property
#abstract Typed access to the user's current city.
*/
#property (retain, nonatomic) id<FBGraphLocation> location;
The FBGraphLocation API has those properties available:
/*!
#property
#abstract Typed access to a location's street.
*/
#property (retain, nonatomic) NSString *street;
/*!
#property
#abstract Typed access to a location's zip code.
*/
#property (retain, nonatomic) NSString *zip;
That's what you need, right?
Finally I used google API to get the latitude and longitude from the address I get from the facebook and using those coordinates I find the zip code.
- (CLLocation *) getGeoCoordinatesUsingAddress: (NSString *) aStrAddres
{
NSString *esc_addr = [aStrAddres stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:BaseURLForLocation, esc_addr];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
NSDictionary *googleResponse =
[NSJSONSerialization JSONObjectWithData: [result dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: nil];
NSDictionary *resultsDict = [googleResponse valueForKey:#"results"];
NSDictionary *geometryDict = [resultsDict valueForKey:#"geometry"];
NSDictionary *locationDict = [geometryDict valueForKey:#"location"];
NSArray *latArray = [locationDict valueForKey: #"lat"]; NSString *latString = [latArray lastObject];
NSArray *lngArray = [locationDict valueForKey: #"lng"]; NSString *lngString = [lngArray lastObject];
CLLocation *locationFound = [[CLLocation alloc] initWithLatitude:[latString doubleValue] longitude:[lngString doubleValue]];
NSLog(#"%s lat: %f\tlon:%f ",__FUNCTION__, [latString doubleValue], [lngString doubleValue]);
return locationFound;
}
Then I used CLGeocoder class
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
for(CLPlacemark *aPlacemark in placemarks){
NSString *strZipCode = [aPlacemark.addressDictionary objectForKey:(NSString *)kABPersonAddressZIPKey];
}
}];
Hope this help..

Filtering an NSDictionary within a dictionary with particular text

I am getting a web service repsonse that is an array of dictionary. Each dictionary has objects whose values itself is another dictionary.I need to implement the search within this response,like if i enter "technology" and go for search, I should get those dictionary from the array that has "technology anywhere within that dictionary", Is there a solution to sort out
{
key1 = {
0 = {
"id" = 608;
"b" = "Apple-Iphone";
};
1 = {
"id" = 609;
"b" = "Iphone";
};
2 = {
"id" = 610;
"b" = "Show Text";
};
};
key2 = "Technology resources";
"key3" = {
0 = {
"id" = 1608;
"b" = "I love reading";
};
1 = {
"id" = 1609;
"b" = "I prefer iphone to others";
};
2 = {
"id" = 1610;
"b" = "Mobile technology is great.I am happy to a be developer";
};
};
"key4" = "Mobile technology is the fun";
}
This is First Method
NSMutableDictionary *dict;
NSArray *allKeys = [dict allKeys];
for (NSString *key in allKeys)
{
NSDictionary *innerDict = [dict objectForKey:key];
NSArray *allInnerKeys = [innerDict allKeys];
for (NSString *innerKey in allInnerKeys)
{
NSDictionary *mostInnerDict = [dict objectForKey:innerKey];
NSString *b = [mostInnerDict objectForKey:b];
NSString *search = #"Technology";
NSString *sub = [b substringFromIndex:NSMaxRange([b rangeOfString:search])];
if(sub)
{
// ADD mostInnerDict Object to your Results Array
}
}
}
Or You can Try The Simpler Method
Get Response in NSDATA
Covert NSDATA To NSString
and search in NSSTRING for Substring

Splitting JSON data in iPhone

I got this data from my server using JSON:
{
ID = 198;
dtDate = "2012-03-14 00:00:00";
dtTime = "06:00:00";
iPublished = 1;
sProgram = "Devotional Hits";
}
{
ID = 199;
dtDate = "2012-03-14 00:00:00";
dtTime = "07:00:00";
iPublished = 1;
sProgram = "Old Malayalam Hits";
}
{
ID = 200;
dtDate = "2012-03-14 00:00:00";
dtTime = "08:00:00";
iPublished = 1;
sProgram = "Malayalam New Hits";
}
{
ID = 201;
dtDate = "2012-03-14 00:00:00";
dtTime = "09:00:00";
iPublished = 1;
sProgram = "Melody Songs";
}
{
ID = 202;
dtDate = "2012-03-14 00:00:00";
dtTime = "10:00:00";
iPublished = 1;
sProgram = "Jayachandran Hits";
}
{
ID = 203;
dtDate = "2012-03-14 00:00:00";
dtTime = "11:00:00";
iPublished = 1;
sProgram = "Yesudas Hits";
}
{
ID = 204;
dtDate = "2012-03-14 00:00:00";
dtTime = "12:00:00";
iPublished = 1;
sProgram = "Ilayaraja Hits";
}
I need to split this data and store sProgram data into an array.. need help.
I need to split this format and I want sProgram and dtTime separately. What should I do for that. I'm a little bit confused about string formatting.
If you are using < IOS 5, add SBJSON to your project
//in some.m file
#import JSON.h
// Lets say NSString *recievedValue contains your JSON response.
id jsonRep = [receivedValue jsonValue];
if([jsonRep isKindOfClass:[NSArray class]])
{
// returned JSON Value has a array structure.
NSArray *value = (NSArray *)jsonRep;
//You can access values using objectAtIndex: method if you already know the Index of a value, in your case i think each array object is a NSDictionary
if([[value objectAtIndex:0] isKindOfClass:[NSDictionary class]])
{
// returned JSON Value has a key value compliant structure.
NSDictionary *dicValue = (NSDictionary *)[value objectAtIndex:0];
//You can access values using objectForKey: method if you already know the key value, in your case it can be #"sProgram" for example
}
}
else if([jsonRep isKindOfClass:[NSDictionary class]])
{
// returned JSON Value has a key value compliant structure.
NSDictionary *value = (NSDictionary *)jsonRep;
//You can access values using objectForKey: method if you already know the key value, in your case it can be #"sProgram" for example
}
Your JSON is invalid - I recommend that you use this tool to check this before posting about a JSON-related issue in the future.
However, I have corrected your JSON and validated it - it should look like this:
[
{
"ID": 198,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "06:00:00",
"iPublished": 1,
"sProgram": "Devotional Hits"
},
{
"ID": 199,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "07:00:00",
"iPublished": 1,
"sProgram": "Old Malayalam Hits"
},
{
"ID": 200,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "08:00:00",
"iPublished": 1,
"sProgram": "Malayalam New Hits"
},
{
"ID": 201,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "09:00:00",
"iPublished": 1,
"sProgram": "Melody Songs"
},
{
"ID": 202,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "10:00:00",
"iPublished": 1,
"sProgram": "Jayachandran Hits"
},
{
"ID": 203,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "11:00:00",
"iPublished": 1,
"sProgram": "Yesudas Hits"
},
{
"ID": 204,
"dtDate": "2012-03-14 00:00:00",
"dtTime": "12:00:00",
"iPublished": 1,
"sProgram": "Ilayaraja Hits"
}
]
You can then use the json-framework to parse it.
As you asked, here is how you can now obtain all the values of sProgram:
NSMutableArray *programs = [[NSMutableArray alloc] init];
NSArray *data = [json jsonValue];
for (NSDictionary *dict in data) {
[programs addObject:[dict objectForKey:#"sProgram"]];
}
// programs now contains all the values of sProgram
actually i used Stig Brautaset’s JSON library (version 2.2)
- (void)viewDidLoad
{
[super viewDidLoad];
[table reloadData];
NSMutableData *responseData;
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://ganamradio.com/smartphones/date.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view from its nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//[responseData release];
dict=[responseString JSONValue];
NSArray *Programs;
NSArray *Time;
Programs=[dict valueForKey:#"sProgram"];
Time=[dict valueForKey:#"dtTime"];
NSLog(#"......%#",Time);
}
so i got the program list in NSArray programs,, is their any problem using like this..?

How to get values from unknown key in NSDictionary iphone?

I have one more big problem while parse the values from Webservice response. I dont know the key for the values in the webservice response. For example,
class = (
{
"ObjectiveC" =
(
{
"brief_desc" = "ObjectiveC";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-12";
"event_status" = Missed;
},
);
},
{
"Java" = (
{
"brief_desc" = "Java";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-12";
"event_status" = Missed;
},
);
}
);
In this response even we dont know the keys "ObjectiveC" and "Java". The keys("ObjectiveC and Java") should be change in every response retured. How to get values of key (Unknown key)? How can i parse this response and get the values?
I would enumerate through the keys to get the value. Here is an example of enumeration in objective-c.
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
//assuming value will be string
NSString *valueForKey = [myDictionary valueForKey:key];
//assuming value is another dictionary
NSDictionary *subDictionary = [myDictionary objectForKey:key];
}
And if you don't know the keys of the sub dictionaries, you can enumerate through those as well.
NSDictionary has - (NSArray *)allKeys and - (NSArray *)allValues. One of those might help
NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"Key", #"Value", #"Key 2", #"Value 2", nil];
NSArray *values = [lessonDict allValues];
NSArray *keys = [lessonDict allKeys];
NSLog(#"Keys: %#",keys);
NSLog(#"Values: %#",values);

How do I properly populate the UITableView NSArray from a NSDictionary created using JSONKit?

Sorry for the long question but that best summarizes what I am trying to do:
My JSON Looks like:
{
4e8cf1d6c7e24c063e000000 = {
"_id" = {
"$id" = 4e8cf1d6c7e24c063e000000;
};
author = faisal;
comments = (
{
author = adias;
comment = amazing;
},
{
author = nike;
comment = "I concur";
}
);
created = {
sec = 1317772800;
usec = 0;
};
text = "This is a random post";
title = "post # 1";
type = (
punjabi
);
};
4e91fd49c7e24cda74000000 = {
"_id" = {
"$id" = 4e91fd49c7e24cda74000000;
};
author = draper;
comments = (
{
author = adias;
comment = "amazing again";
}
);
created = {
sec = 1318118400;
usec = 0;
};
text = "This is a random post again";
title = "post # 2";
type = (
punjabi
);
};
}
What I would like to do is to ultimately have a UTTableview with each row having a title (text from above JSON):
This is the code I have so far:
NSString *responseString = [request responseString];
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
How do I put everything in an array for the UITableView? Again I am just a little rusty as I can swear I have done that before.
If you don't need the keys then you can convert it to an array by using allValues, e.g.:
NSArray *values = [resultsDictionary allValues];
Does your JSON really parse to an NSDictionary, or is this an NSArray containing NSDictionary instances? If the latter, then isn't it just something like:
NSString *textForCell = [[resultsArray objectAtIndex:row] valueForKey:#"title"];