Unable to extract the keys from a JSON response - iphone

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.
}

Related

How to display string value in label when the value is null and some number

I have JSON object like this.
{
"id": "1",
"subTotal": "20000.00",
"total": "124565.00",
"timeOfTrans": "3555525",
"status": "1",
"name": "gjgjgf",
"email": "a#a.com",
"level": "gjfgj",
"teamId": "1"
},
{
"id": "2",
"subTotal": null,
"total": null,
"timeOfTrans": null,
"status": null,
"name": "Rajendra",
"email": "b#b.com",
"level": "gfjgfjg",
"teamId": "1"
}
I want to display JSON string "total" in label. When "total" is null i want to display '0' when "total" is some number i want to display that number in same label.
Here i`m trying this code
totalLbl=(UILabel *)[cell viewWithTag:1];
id total = [currentEmplyCellDit objectForKey:#"total"];
if ([total isKindOfClass:(id)[NSNull null]])
{
//Your value of total is NULL
totalLbl.text = #"0";
}
//Show the Value.
totalLbl.text = [NSString stringWithFormat:#"%#",total];
this code displaying correctly but i shows null in label when "total" is null.
I want to display 0 when "total" is NULL
How to Solve this...
Thanks.
You can make condition to check null in your string and then replace this with whatever you want.
id yourValue=[youJSONDict objectForKey:#"total"];;
if ([yourValue isKindOfClass:[NSNull class]]) {
yourLabel.text=#"0";
}
else{
yourLabel.text=[NSString stringWithFormat:#"%#",yourValue];
}
Try this :
if([dictionary valueForKey:#"total"] != nil) {
// The key existed..
}
else {
// No joy...
}
And remember this thing
:
objectForKey will return nil if a key doesn't exist
Symbol Value Meaning
======= ============= =========================================
NULL (void *)0 literal null value for C pointers
nil (id)0 literal null value for Objective-C objects
Nil (Class)0 literal null value for Objective-C classes
NSNull [NSNull null] singleton object used to represent null
and see my answer Checking a null value from Json response in Objective-C
Just call one of these function using the dictionary or array whatever you are receiving from the JSON. These functions will remove all NULL values from your response.
You have to write both functions they are calling each other recursively.
Call like these...
NSMutableDictionary * ResponseDict =(NSMutableDictionary *)[responseString JSONValue];
ResponseDict = [self removeNullFromDictionary:ResponseDict];
NSLog(#"ResponseDict = %#",ResponseDict);
This is the function for Dictionary.
-(NSMutableDictionary *)removeNullFromDictionary : (NSMutableDictionary *)dict
{
for (NSString * key in [dict allKeys])
{
if ([[dict objectForKey:key] isKindOfClass:[NSNull class]])
{
[dict setValue:#"" forKey:key];
}
else if ([[dict objectForKey:key] isKindOfClass:[NSMutableDictionary class]]||[[dict objectForKey:key] isKindOfClass:[NSDictionary class]])
{
[dict setObject:[self removeNullFromDictionary:[dict objectForKey:key]] forKey:key];
}
else if ([[dict objectForKey:key] isKindOfClass:[NSMutableArray class]]||[[dict objectForKey:key] isKindOfClass:[NSArray class]])
{
[dict setObject:[self removeNullFromArray:[dict objectForKey:key]] forKey:key];
}
}
return dict;
}
This is the function for array
-(NSMutableArray *)removeNullFromArray : (NSMutableArray *)arr
{
for (int cnt = 0; cnt<[arr count]; cnt++)
{
if ([[arr objectAtIndex:cnt] isKindOfClass:[NSNull class]])
{
[arr replaceObjectAtIndex:cnt withObject:#""];
}
else if ([[arr objectAtIndex:cnt] isKindOfClass:[NSMutableDictionary class]]||[[arr objectAtIndex:cnt] isKindOfClass:[NSDictionary class]])
{
[arr replaceObjectAtIndex:cnt withObject:[self removeNullFromDictionary:(NSMutableDictionary *)[arr objectAtIndex:cnt]]];
}
else if ([[arr objectAtIndex:cnt] isKindOfClass:[NSMutableArray class]]||[[arr objectAtIndex:cnt] isKindOfClass:[NSArray class]])
{
[arr replaceObjectAtIndex:cnt withObject:[self removeNullFromArray:(NSMutableArray *)[arr objectAtIndex:cnt]]];
}
}
return arr;
}
This will definitely help you. Must try.....
if([currentEmplyCellDit objectForKey:#"total"] == [NSNull null])
{
yourLbl.text=#"0";
}
else
{
yourLbl.text = [currentEmplyCellDit objectForKey:#"total"]
}

how to check valueOfKey is Array or Object when we get it from json in ios

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
}

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

IOS JSON get all values from a "JSON Dict"

i have this data structure :
{
"artistlist " : [
{
"performer" : "Gate Zero"
},
{
"performer" : "nightech"
},
{
"performer" : "Marko Fuerstenberg"
},
]
}
I read this structure from NSString into NSDictionary with this line of code:
JSON = [NSJSONSerialization JSONObjectWithData:
[[chunks objectAtIndex:1]
dataUsingEncoding:NSUTF8StringEncoding] options:
NSJSONReadingMutableContainers error: &e];
with: [JSON objectForKey:#"artistlist "] i get this structure:
(
{
performer = "Gate Zero";
},
{
performer = nightech;
},
{
performer = "Marko Fuerstenberg";
}
)
Is there any way to go "deeper" ?
how would i parse the resulting Structure ?
I would like to get a list of values or access performer names directly. What if i have several values in a tupel for example performer name, album, year. How would i access those values?
Thank you.
Yes, after you have [JSON objectForKey:#"artistlist "], you get an NSArray of NSDictionaries (slightly confusing!).
NSArray *performersArray = [JSON objectForKey:#"artistlist"];
for (NSDictionary *performerDic in performersArray) {
NSLog(#"%#", [performerDic objectForKey:#"performer"]);
}
This should yield each performer name. Alternatively, you can do for (NSUInteger i = 0; i < [performersArray count]; i++) and access NSDictionary *performersDic = [performersArray objectAtIndex: i]. From there, you can similarly use [performsDic objectForKey:#"performer"]
Like this:
[[[JSON objectForKey:#"artistlist "] objectAtIndex: 1] objectForKey:#"performer"]
It will give you "nightech".
{} corresponds to NSDictionary, [] corresponds to NSArray.
You'll have to use recursion. For example, assuming you have only nested NSDictionaries (easy to modify to work with NSArrays):
- (void) getArtistFromJsonObject:(NSDictionary *)obj {
for (NSString *key in [obj allKeys]) {
id child = [obj objectForKey:key];
if ([child isKindOfClass:[NSString class]]) {
// that's the actual string
// NSLog(#"Found artist: %#", child); // or do whatever needed
} else if ([child isKindOfClass:[NSDictionary class]]) {
[self getArtistFromJsonObject:child];
}
}
}

Facebook sdk for ios read fan page wall

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 :)