Error on JSON parsing - iphone

I'm having a problem on parsing a JSON.
That is my code.
-(void)requstJson1:(ASIHTTPRequest *)request
{
jsonResponse = [request responseString];
jsonDic = [jsonResponse JSONValue];
jsonResult = [[jsonDic valueForKey:#"events"] retain];
type=[[jsonResult valueForKey:#"time"] retain];
data=[[jsonResult valueForKey:#"data"] retain];
NSDictionary *dic=[data JSONValue];
hp=[[dic valueForKey:#"hp"] retain];
}
That is my JSON Response
{
"result": "ok",
"totalcount": 422,
"events": [
{
"id": "52982168e4b00e53abdace66",
"deviceId": "203",
"channelId": "",
"data": "{\"hp\":\"6586129568\",\"camID\":\"camID120\",\"device_id\":38,\"pairedDeviceId\":\"204\"}",
"longitude": 103.82,
"latitude": 1.352,
"type": "event-intercom-visitor-alert",
"time": "29/11/2013 05:09:54",
"blobId": "",
"messageCount": 0,
"patchEventVideoURL": "",
"deviceName": "Intercom"
}
]
}
I get all the response but i am not getting this "{\"hp\":\"6586129568\",\"camID\":\"camID120\",\"device_id\":38,\"pairedDeviceId\":\"204\"}"
And get error like this -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1c5cb310
2013-11-29 12:37:33.280 Intercom[14720:907] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1c5cb310'
* First throw call stack:
Thank you

try this ...
-(void)requstJson1:(ASIHTTPRequest *)request
{
jsonResponse = [request responseString];
jsonDic = [jsonResponse JSONValue];
NSString * jsonResult = [[jsonDic valueForKey:#"events"] retain];
NSString * type=[[jsonResult valueForKey:#"time"] retain];
NSArray * array=[[jsonResult valueForKey:#"data"] retain];
NSDictionary * data = [array objectAtIndex:0];
NSString * hp = [data objectForKey:#"hp"];
NSString * camID = [data objectForKey:#"camID120"];
NSString * device_id = [NSString stringWithFormat:#"%d",[data valueForKey:#"device_id"]];
...........
}

If you can control the JSON output, you should definitely avoid JSON as string in JSON. You can nest JSON as deep as you want.
The problem is that the string in your data key is not JSON. It's escaped, so it cannot be read.
You should use NSJSONSerialization or any similar JSON parser. NSJSONSerialization is integrated in iOS, so you should try it:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[[response responseString] dataUsingEncoding:NSUTF8StringEncoding]];
You can also use the response data directly, but I don't know ASIHTTP very well.

Sorry for that trouble the JSON is not properly formatted the correct example is :
{
"result": "ok",
"totalcount": 422,
"events": [
{
"id": "52982168e4b00e53abdace66",
"deviceId": "203",
"channelId": "",
"data": {\"hp\":\"6586129568\",\"camID\":\"camID120\",\"device_id\":38,\"pairedDeviceId\":\"204\"},
"longitude": 103.82,
"latitude": 1.352,
"type": "event-intercom-visitor-alert",
"time": "29/11/2013 05:09:54",
"blobId": "",
"messageCount": 0,
"patchEventVideoURL": "",
"deviceName": "Intercom"
}
]
}

Related

Converting JSON Data from NSData to NSDictionary

I have a PHP service that returns me the following response in NSData format. After converting the same into NSString using:
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
I get the following:
[
{
"Emp_Name": "Krishna Mamidi",
"Emp_Designation": "Driver",
"Emp_Type": "Permanent",
"Joining_Date": "05-MAR-2011",
"Salary": 10000
},
{
"Emp_Name": "Aditya Reddy",
"Emp_Designation": "supervisor",
"Emp_Type": "Permanent",
"Joining_Date": "06-MAR-2011",
"Salary": 9000
},
{
"Emp_Name": "Rajiv krishna",
"Emp_Designation": "director",
"Emp_Type": "Permanent",
"Joining_Date": "01-MAR-2011",
"Salary": 100000
}
]
The above is in correct JSON Format.
Having received the NSData format of the above, I use the following to convert the same into JSON Dictionary:
NSError *error = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONWritingPrettyPrinted error:&error];
NSDictionary *deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
}
}
However the "deserializedDictionary" is always null or empty. Basically it never came inside the If Loop above.
I have been trying to figure this out for a while and am not able to. Please help
Your json object is an array try with NSArray instead of NSDictionary.
Because the JSON returned is an array, not a dictionary. Try:
NSLog(#"%#", NSStringFromClass([jsonObject class]));

Couldn't parse data using Json on IOS 5

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

how to json parse with components Separated By String

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

parsing json in iphone

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"] ;

How to fetch data from this specific json (iphone)

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"]);
}