I ve got a twitter json Feed.the thing is i m getting error while parsing the json feed .i m using jsonkit.below is the json url.i want to parse the value text and profile_background_image_url in the below json feed.cud u guys help me out
[
{
"created_at": "Mon Jul 09 21:46:49 +0000 2012",
"id": 222446736654872580,
"id_str": "222446736654872576",
"text": "#mevru you have to go to : http://t.co/pPGYijEX",
"source": "web",
"truncated": false,
"in_reply_to_status_id": 222445085235752960,
"in_reply_to_status_id_str": "222445085235752961",
"in_reply_to_user_id": 146917266,
"in_reply_to_user_id_str": "146917266",
"in_reply_to_screen_name": "mevru",
"user": {
"id": 145125358,
"id_str": "145125358",
"name": "Amitabh Bachchan",
"screen_name": "SrBachchan",
"location": "Mumbai, India",
"description": "Actor ... well at least some are STILL saying so !!",
"url": "http://srbachchan.tumblr.com",
"protected": false,
"followers_count": 3022511,
"friends_count": 415,
"listed_count": 22016,
"created_at": "Tue May 18 05:16:47 +0000 2010",
"favourites_count": 10,
"utc_offset": 19800,
"time_zone": "Mumbai",
"geo_enabled": false,
"verified": true,
"statuses_count": 14166,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"profile_background_color": "BADFCD",
"profile_background_image_url": "http://a0.twimg.com/profile_background_images/144221357/t-1.gif",
"profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/144221357/t-1.gif",
"profile_background_tile": true,
"profile_image_url": "http://a0.twimg.com/profile_images/2227330575/Amitji_normal.png",
"profile_image_url_https": "https://si0.twimg.com/profile_images/2227330575/Amitji_normal.png",
"profile_link_color": "FF0000",
"profile_sidebar_border_color": "F2E195",
"profile_sidebar_fill_color": "FFF7CC",
"profile_text_color": "0C3E53",
"profile_use_background_image": true,
"show_all_inline_media": true,
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": null,
"notifications": null
}
following is the ios code that i used to parse
jsonurl=[NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=#SrBachchan&count=10"];
jsonData=[[NSString alloc]initWithContentsOfURL:jsonurl];
jsonArray = [jsonData objectFromJSONString];
items = [jsonArray objectForKey:#"text"];
NSLog(#"the given text:%#",items);
story = [NSMutableArray array];
title = [NSMutableArray array];
picture = [NSMutableArray array];
for (NSDictionary *item in items )
{
}
The problem is in this line:
items = [jsonArray objectForKey:#"text"];
As your code suggest it's an array not a dictionary thus you have grab the object from the array first:
for (NSDictionary *item in jsonArray ) {
NSDictionary *user = [item objectForKey:#"user"];
NSString *imageURLString = [user objectForKey:#"profile_image_url"];
}
NSData *data = [NSData dataWithContentsOfURL:jsonurl];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (!array) return;
NSDictionary *dictionary = [array objectAtIndex:0];
if (dictionary){
NSString *text = [dictionary valueForKey:#"text"];
NSString *profileBackgroundImageURL = [dictionary valueForKeyPath:#"user.profile_background_image_url"];
}
Use jsonlint.com to validate your JSON.
The error is lacking of the last closing operand } at the end of JSON string.
There're 2 opening but only one closing.
Parse error on line 52:
...cations": null }
----------------------^
Expecting '}', ',', ']'
Try this
items = [[jsonArray objectAtIndex:0] objectForKey:#"text"];
backImage=[[[jsonArray objectAtIndex:0] objectForKey:#"user"] objectForKey:#"profile_background_image_url"] ;
Related
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.
}
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
Hi I have implemented code for parsing the below response as follows but it is not working properly:
NSString *req = [NSString stringWithFormat: #" My URL"];
NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];
NSDictionary *resultsDict = [googleResponse valueForKey: #"eventtitle"];
What is the code for parsing the below response? Please give me solution.
{
"AlansHarleyEvents": [
{
"id": "3",
"eventtitle": "22nd Annual Pig Roast",
"eventdate": "April 22nd 8am-5pm"
},
{
"id": "4",
"eventtitle": "Poker Run",
"eventdate": "April 28th 8am at Shooters"
},
{
"id": "5",
"eventtitle": "Kickstands for kids",
"eventdate": "May 12th 8am-5pm"
},
{
"id": "6",
"eventtitle": "Ride for the Cure",
"eventdate": "May28th 8am Free Drinks!"
},
{
"id": "7",
"eventtitle": "Veterans Ride",
"eventdate": "June 10th 9am #City Hall"
},
{
"id": "8",
"eventtitle": "Biker Beach Bash",
"eventdate": "June 28th 8-5pm # The Pier"
},
{
"id": "10",
"eventtitle": "22nd Annual Pig Roast",
"eventdate": "April 22nd 8am-5pm"
},
{
"id": "11",
"eventtitle": "Poker Run",
"eventdate": "April 28th 8am at Shooters Lounge"
},
{
"id": "12",
"eventtitle": "22nd Annual Pig Roast",
"eventdate": "April 22nd 8am-5pm"
},
{
"id": "13",
"eventtitle": "Swamp Run",
"eventdate": "April 22nd 8am-5pm"
}
]
}
If your resultsDict contains the above JSON response then you can parse it as :
NSString *req = [NSString stringWithFormat: #" My URL"];
NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];
NSDictionary *resultsDict = [googleResponse valueForKey: #"eventtitle"];
NSMutableArray *resultArray = [resultsDict valueForKey:#"AlansHarleyEvents"];
for(int i = 0; i<[resultArray count]; i++)
{
NSLog(#"%#",[[resultArray objectAtIndex:i] valueForKey:#"id"]) ;
NSLog(#"%#",[[resultArray objectAtIndex:i] valueForKey:#"eventtitle"]) ;
NSLog(#"%#",[[resultArray objectAtIndex:i] valueForKey:#"eventdate"]) ;
}
NSJSONSerialization Class is the Native Class for only iOS 5 and above
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
For any iPhone OS version means you can go for JSONKit:
https://github.com/johnezang/JSONKit
Yu can use NSJSONSerialization object with IOS 5
NSDictionnary *jsonObject = [NSJSONSerialization JSONObjectWithData:resultsDict options:NSJSONReadingMutableContainers error:&error];
Can anyone tell me how to find the model from this ?
it is giving me null all the time
{
"Status": 200,
"Data": [
{
"id": "1",
"custno": "0000235",
"locno": "00001",
"mfg": "KABA-MAS",
"model": "Cencon Gen II",
"serial": "GF8912",
"install": "2011-10-01",
"removed": "0000-00-00",
"warranty": "2012-01-10",
"seragrno": "A",
"equiploc": "Testing",
"notes": "This is a test lock to test our system. I this is it good.",
"invoice": "A",
"eqtype": "Lock",
"plan": "1",
"status": "0",
"image": "cencon_main_1318703242.gif",
"pmrequired": "1",
"locktime": null,
"lockby": null,
"pmrequiredText": "Yes",
"statusText": "Active",
"planTypeText": "Plan I"
},
{
"id": "2",
"custno": "0000235",
"locno": "00001",
"mfg": "adsdad",
"model": "",
"serial": "",
"install": "2011-10-24",
"removed": "0000-00-00",
"warranty": "0000-00-00",
"seragrno": "",
"equiploc": "",
"notes": "",
"invoice": "",
"eqtype": "",
"plan": "",
"status": "-1",
"image": "",
"pmrequired": "0",
"locktime": null,
"lockby": null,
"pmrequiredText": "No",
"statusText": "Pending",
"planTypeText": null
}
]
}
I am not sure...but there should be some obj.value type of structure, like in javascript
u can access it using something like "responce.data.model"
assuming the JSON has been turned into an NSDictionary:
NSArray *items = [dictionary objectForKey:#"Data"];
for (item in items) {
NSLog(#"model = %#", [item objectForKey:#"model"]);
}
If you are looking for how to turn the JSON into an NSDictionary try:
iPhone/iOS JSON parsing tutorial
try this :
NSData *responseData;
NSMutableDictionary *response ;
NSString *urlStr = [NSString stringWithFormat:#"http://www.example.com"];
NSLog(#"%#",urlStr);
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *json = [[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] autorelease];
response = (NSMutableDictionary *)[json JSONValue];
Then you'll have dictionary response. Now you can access it as
NSLog(#"%#",[response valueForKey:#"Data"] objectAtIndex:yourIndexValue] valueForKey:#"model"]);
Use SBJsonParser for parsing the response.
And "data" field is array of dictionary.
SBJsonParser *parser = [[SBJsonParser alloc] init];
// parsing the JSON
NSMutableDictionary *jsonDictionary = [parser objectWithString:response];
NSMutableArray *dataArray = [jsonDictionary objectForKey:#"data"];
So, u can use something like this:-
for(NSMutableDictionary *tempDictionary in dataArray)
{
NSLog(#"id is %#",[dataArray objectForKey: #"description"]);
}
I get a return array by json,
[{"date": "2011-01-01", "title": "aaa"},
{"date": "2011-01-01", "title": "bbb"},
{"date": "2011-01-01", "title": "ccc"},
{"date": "2011-01-02", "title": "ddd"},
{"date": "2011-01-02", "title": "eee"},
{"date": "2011-01-03", "title": "fff"},
{"date": "2011-01-03", "title": "ggg"}]
I use these code to get the value:
NSDictionary *jsonDictionary = [jsonArray objectAtIndex:i];
NSString *date = [jsonDictionary objectForKey:#"dispalyDate"];
NSString *title = [jsonDictionary objectForKey:#"title"];
The problem is how can I restructure the array or create new array according to the same date, such as
date = 2011-01-01
aaa、bbb、ccc
date = 2011-01-02
ddd、eee
date = 2011-01-03
fff、ggg
Something like this...
NSMutableDictionary *titlesByDate = [NSMutableDictionary dictionary];
for (NSDictionary *entry in jsonDictionary) {
NSString *date = [entry objectForKey:#"date"];
NSMutableArray *titles = [titlesByDate objectForKey:date];
if (!titles) {
titles = [NSMutableArray array];
[titlesByDate setObject:titles forKey:date];
}
[titles addObject:[entry objectForKey:#"title"]];
}
Now you have a dictionary where the keys are date strings and the values are title arrays. If you really want an array result, you can then do this:
NSMutableArray *array = [NSMutableArray array];
for (NSString *date in titlesByDate) {
[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:
date, #"date",
[titlesByDate objectForKey:date], #"titles",
nil];
}