i want to read my fan page wall from my iPhone application, how i can do ?
Now i have this code for parse the graph api:
-(IBAction)parsing:(id)sender{
[facebook requestWithGraphPath:#"PAGE_ID/feed" andDelegate:self];
}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"received response");
}
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
// NSArray *data = [result objectForKey:#"data"];
NSArray *from = [result objectForKey:#"from"];
if ([result objectForKey:#"from"]) {
for (NSDictionary *name in from) {
NSString *myName = [name objectForKey:#"name"];
[self.label2 setText:myName];
NSLog(#" Log: ", myName);
}
But don't work because he don't parse:
The json file i want to parse is this:
{
"data": [
{
"id": "105744066144184_231235146928408",
"from": {
"name": "Alberto ####",
"id": "1000013568710###"
},
"to": {
"data": [
{
"name": "########",
"category": "News/media",
"id": "##########"
}
]
},
"message": "\u00e8######################################",
"type": "status",
"created_time": "2011-09-02T18:30:59+0000",
"updated_time": "2011-09-02T18:30:59+0000",
"likes": {
"data": [
{
"name": "Luca #####",
"id": "###########"
}
],
"count": 1
},
"comments": {
"count": 0
}
ecc..
I use
NSArray *list = [result valueForKey:#"data"];
for (NSDictionary *dic in list) {
NSLog(#"id : %#",[dic valueForKey:#"id"]);
NSLog(#"type : %#",[dic valueForKey:#"type"]);
if ([[dic valueForKey:#"type"] isEqualToString:#"status"]) {
NSLog(#"- message : %#",[dic valueForKey:#"message"]);
}else if([[dic valueForKey:#"type"] isEqualToString:#"link"]){
NSLog(#"- link : %#",[dic valueForKey:#"link"]);
}else if([[dic valueForKey:#"type"] isEqualToString:#"photo"]){
NSLog(#"- icon : %#",[dic valueForKey:#"icon"]);
NSLog(#"- message : %#",[dic valueForKey:#"message"]);
}
NSLog(#"------");
}
adaydesign :)
Related
I have 2 cases to parse JSON First is:
{
"post_filter_data": {
"Items": [
{
"ItemID": "50cb4e46b5d30b0002000009",
"ItemName": "Fruit salad test",
"ItemPrice": "122.0",
"ItemDescription": "test test",
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50cb4e64b5d30b0002000013/landing_page.jpg?1355501156"
},
{
"ItemID": "50d0870d910ef2000200000a",
"ItemName": "test new",
"ItemPrice": "120.0",
"ItemDescription": null,
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50d0871a910ef20002000015/Screenshot-2.png?1355843354"
}
]
}
}
in which Items is an NSArray and it's parse easily but when only one object I get its through exception.
Second JSON is in which Items tag has one one object:
{
"post_filter_data": {
"Items": {
"ItemID": "50d1e9cd9cfbd20002000016",
"ItemName": "test",
"ItemPrice": "120.0",
"ItemDescription": "test",
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50d1ea019cfbd20002000022/11949941671787360471rightarrow.svg.med.png?1355934209"
}
}
}
and my code is here In which I am parsing it:
NSDictionary *dictMenu=[responseDict valueForKey:#"post_filter_data"];
NSArray* subMenuArray=[dictMenu valueForKey:#"Items"];
Is there any way in which I check it out that valueForKey:#"Items" is Array or Object.
Get data rx in _recievedData then check the class of the object.
id object = [NSJSONSerialization
JSONObjectWithData:_recievedData
options:kNilOptions
error:&error];
if (error)
{
NSLog(#"Error in rx data:%#",[error description]);
}
if([object isKindOfClass:[NSString class]] == YES)
{
NSLog(#"String rx from server");
}
else if ([object isKindOfClass:[NSDictionary class]] == YES)
{
NSLog(#"Dictionary rx from server");
}
else if ([object isKindOfClass:[NSArray class]] == YES)
{
NSLog(#"Array rx from server");
}
Yes, you can check using class like
if ([[dictMenu valueForKey:#"Items"] isKindOfClass:[NSArray class]])
{
// array inside
}
Following is valid JSON Response:
**{
"responseHeader": null,
"cart": {
"locale": "en_US",
"currency": "USD",
"purchaseRequestId": 0,
"stuid": 0,
"defaultHeaderLineLevels": {},
"invalidMaterialIDs": [
{
"#class": "com.insight.web.domain.transaction.LineItem",
"ewrFee": null,
"name": null,
"currency": null,
"description": null,
"categoryId": null,
"poolID": null,
"contractReportingFields": {},
"selectedwarrantyDetails": null,
"manufacturerName": null,
"warrantyDetails": [],
"vspp": false,
"softwareLicense": false,
"sourceContractId": null,
"softwareLicenseType": "",
"nonShipabble": false,
"configured": false,
"partnerID": null,
"cartModifiedByConvertQuote": false,
"stock": 0,
"deletable": false,
"duplicatable": false,
"softwareLicensePhone": null,
"softwareLicenseName": null,
"zp00MaterialCategory": false,
"quotedShippingPrice": null,
"diversityPartners": [],
"labFeesExists": false,
"quoteConfigured": false,
"quotedOrderConditions": null,
"ruleID": ""
},
{
"#class": "com.insight.web.domain.transaction.LineItem",
"ewrFee": null,
"name": null,
"currency": null,
"description": null,
"selectPlus": false,
"lineLevels": {},
"materialID": "4434HE1-OPY",
"materialIDKey": "",
"isDiscontinued": false,
"itemNumber": null,
"quoteItemNumber": null,
"price": 0,
"quantity": 0,
"materialCategory": null,
"ruleID": ""
}
],
"webLoginProfile": null,
"requestorGroupId": null,
"defaultLineLevels": {},
"totalCost": 0,
"dpasCode": null,
"orderedDate": null,
"hasSPLAAndNonSPLAContracts": false,
"cartItemsForEmail": [],
},
"materialIdKeyList": []
}
To extract all the keys from it I am using the recursive function passing the JSON response as dictionary object "data":
-(NSMutableDictionary *)recurse:(NSDictionary *)data counter:(NSInteger *)i parent:(NSString *)parent
{
self.mDict = [NSMutableDictionary dictionary];
for (NSString* key in [data allKeys])
{
NSDictionary
*value = [data objectForKey:key];
if ([value isKindOfClass:[NSDictionary class]])
{
i++;
NSDictionary *newDict = (NSDictionary*)value;
[self recurse:newDict counter:i parent:key];
[self.mDict setValue:value forKey:key];
i--;
if(i==0)
{
return self.mDict;
}
}
else if([value isKindOfClass:[NSArray class]])
{
// loop through the NSArray and traverse any dictionaries found
NSArray *a = (NSArray *)value;
for(id child in a)
{
if([child isKindOfClass:[NSDictionary class]])
{
i++;
NSDictionary *newDict = (NSDictionary *)child;
[self recurse:newDict counter:i parent:key];
[self.mDict setValue:value forKey:key];
i--;
if(i==0)
{
return self.mDict;
}
}
else
{
[self.mDict setValue:value forKey:key];
}
}
}
else
{
[self.mDict setValue:value forKey:key];
}
}
return self.mDict;
}
The output only gives 3 keys-values pairs for keys: postLoginRedirectUrl,
cart,
defaultHeaderLineLevels....I mean its absurd. What other conditions should i include ?or is there a easy way to get all the keys from the JSON response which is my true goal.
Can you please convert the NSString into NSData and try the following line of code?
NSDictionary *dictionaryResponse = [NSJSONSerialization JSONObjectWithData:[stringResponse dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];
Try The Following Code and let me know the feedback.
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
if ([jsonObject respondsToSelector:#selector(objectForKey:)])
{
NSDictionary *cart_Dict=[jsonObject valueForKey:#"cart"];
NSString *responseHeader=[jsonObject valueForKey:#"responseHeader"];
NSArray *invalidMaterial_CartDict_array=[[jsonObject valueForKey:#"cart"] objectForKey:#"invalidMaterialIDs"];
NSArray *materialIdKeyList_array=[[jsonObject valueForKey:#"materialIdKeyList"]
}
if you dont know what is the respond string then you have to find all Keys
if ([jsonObject isKindOfClass: [NSArray class]])
{
//for Array you have to access by Object at Index
}
else if ([jsonObject isKindOfClass: [NSDictionary class]])
{
for (NSString *key in [jsonObject allKeys])
{
NSDictionary *feed = [jsonObject objectForKey:key];
//do stuff with feed.
}
}
else
{
// deal with it.
}
I try to grab some data with json on ios 5. but i fail...
could someone help me and tell me why it didn't work out.
here's my implementation code
define :
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:#"http://jaksport.com/jarray.php"] //2
then in the viewdidload :
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
this is the function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* key = [json objectForKey:#"price"]; //2
NSLog(#"value: %#", key); //3
}
this is the json file:
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
},
{
"id":2,
"name":"Wicked Wolf",
"beer":5,
"cider":4.5,
"guinness":4
},
{
"id":3,
"name":"Cafe Posh",
"beer":6,
"cider":5.5,
"guinness":5.5
},
{
"id":4,
"name":"My House",
"beer":16,
"cider":15.5,
"guinness":15.5
}
]
}
}
the nslog always print out null value
The error is in how you acces the objects in your JSON :
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
}
}
Given a JSON like that to access the price array you use a syntax like this
NSArray *price = [[json objectForKey:#"prices"]objecForkey:#"price"];
Check the URL in web browser, Your URL is Not A proper JSON.
Link for JSON Verification : JSON Verification
im new to parsing JSON and im trying a simple task, to retrieve a URL from a forecast weather json file.
Here i parse the json and i NSLog the contents of each component of the data:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *data = [res objectForKey:#"data"];
NSLog(#"data=%#",data);
NSArray *results = [data valueForKey:#"weather"];
NSLog(#"weather=%#",results);
NSArray *results1 = [results valueForKey:#"tempMaxC"];
NSLog(#"tempMaxC=%#",results1);
NSArray *results2 = [results1 valueForKey:#"weatherIconUrl"];
NSLog(#"weatherIconUrl=%#",results2);
The problem is that when i get the WeatherIconUrl it comes with this format
"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
and i cant get the url itself without the quotation marks, i tried using nsrange and componentsSeparatedByString but it always gives me this error:
[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance
JSON from server:
{
"data": {
"current_condition": [
{
"cloudcover": "0",
"humidity": "73",
"observation_time": "12:19 PM",
"precipMM": "0.0",
"pressure": "1021",
"temp_C": "23",
"temp_F": "73",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "NW",
"winddirDegree": "320",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "Fanzeres, Portugal",
"type": "City"
}
],
"weather": [
{
"date": "2012-09-12",
"precipMM": "0.0",
"tempMaxC": "28",
"tempMaxF": "83",
"tempMinC": "17",
"tempMinF": "63",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "NW",
"winddirDegree": "312",
"winddirection": "NW",
"windspeedKmph": "16",
"windspeedMiles": "10"
},
{
"date": "2012-09-13",
"precipMM": "0.0",
"tempMaxC": "33",
"tempMaxF": "91",
"tempMinC": "17",
"tempMinF": "63",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "N",
"winddirDegree": "8",
"winddirection": "N",
"windspeedKmph": "10",
"windspeedMiles": "6"
}
]
}
}
Sorry for my bad english and please correct me if im doing this wrong, thanks in advance
use objectForKey instead of valueForKey when getting the array from #"weatherIconUrl" then get the string into NSString e.g.
NSString *weatherIconUrlString = [results2 objectAtIndex:0]
to check that this is a valid url, use the canHandleRequest method of NSURLConnection, e.g.
NSURL *url = [NSURL URLWithString:weatherIconUrlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
BOOL canGo = [NSURLConnection canHandleRequest:request];
If you truly have quotes surrounding your URL, then try something like this:
NSString *someURLString = [results2 objectAtIndex:0];
NSString *quotesRemoved = [someURLString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\""]];
putting the server's output through jsonLint.com gives an easier to read format of the json.
The code below now gets the weather icon url as required. It assumes the json has been downloaded as an NSData object called jsonData, and doesn't check for which date the data refers to.
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves
error:&error];
NSArray *data = [jsonDict valueForKey:#"data"];
NSArray *weather = [data valueForKey:#"weather"];
NSArray *weatherIcon = [[weather objectAtIndex:0] valueForKey:#"weatherIconUrl"];
NSString *url = [[weatherIcon objectAtIndex:0] valueForKey:#"value"];
The resulting url is used in an NSURLRequest and shown in a webview
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..?