so I've been given a task of using a flickr API created by a lecturer, and we have to use it to populate a tableview of a particular user. I'm able to count the number of elements etc, but I can't figure out for the life of me how to actually call the image/photo element of the pair?
This is the code:
- (NSArray *) photosForUser: (NSString *) friendUserName
{
NSString *request = [NSString stringWithFormat: #"https://api.flickr.com/services/rest/?method=flickr.people.findByUsername&username=%#", friendUserName];
NSDictionary *result = [self fetch: request];
NSString *nsid = [result valueForKeyPath: #"user.nsid"];
request = [NSString stringWithFormat: #"https://api.flickr.com/services/rest/?method=flickr.photos.search&per_page=%ld&has_geo=1&user_id=%#&extras=original_format,tags,description,geo,date_upload,owner_name,place_url", (long) self.maximumResults, nsid];
result = [self fetch: request];
return [result valueForKeyPath: #"photos.photo"];
}
What is used to fetch the data:
- (NSDictionary *) fetch: (NSString *) request
{
self.apiKey = #"26225f243655b6eeec8c15d736b58b9a";
NSLog(#"self.APIKey = %#", self.apiKey);
NSString *query = [[NSString stringWithFormat: #"%#&api_key=%#&format=json&nojsoncallback=1", request, self.apiKey]
stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *queryURL = [NSURL URLWithString: query];
NSData *responseData = [NSData dataWithContentsOfURL: queryURL];
if (!responseData)
return nil;
NSError *error = nil;
NSDictionary *jsonContent = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
if (!jsonContent)
NSLog(#"Could not fetch '%#': %#", request, error);
return jsonContent;
}
Can anyone give me any pointers on how I can actually call the image?
Much appreciated.
edit: this is an NSLog output of what's in the JSON array received from the flickr API.
latestPhotos (
{
accuracy = 16;
context = 0;
dateupload = 1397679575;
description = {
"_content" = "<a href=\"https://www.flickr.com/photos/tanjabarnes/\">
};
farm = 3;
"geo_is_contact" = 0;
"geo_is_family" = 0;
"geo_is_friend" = 0;
"geo_is_public" = 1;
id = 13902059464;
isfamily = 0;
isfriend = 0;
ispublic = 1;
latitude = "34.062214";
longitude = "-118.35862";
owner = "66956608#N06";
ownername = Flickr;
"place_id" = "I78_uSpTWrhPjaINgQ";
secret = cc17afe1b3;
server = 2928;
tags = "panorama losangeles beverlyhills tanjabarnes";
title = blahlbah
woeid = 28288701;
}
)
You need to construct the URL of the image using the ids in your JSON array. Like this:
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
So in your example:
http://farm3.staticflickr.com/2928/13902059464_cc17afe1b3.jpg
Here's how you get to your images:
NSArray *photos = [self photosForUser:friendUserName];
for(NSDictionary *dictionary in photos) {
NSString *farmId = [dictionary objectForKey:#"farm"];
NSString *serverId = [dictionary objectForKey:#"server"];
NSString *photoId = [dictionary objectForKey:#"id"];
NSString *secret = [dictionary objectForKey:#"secret"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg", farmId, serverId, photoId, secret]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
// Do something with your image here
}
Reference: https://www.flickr.com/services/api/misc.urls.html
Related
When i got my server response and trying to save that in plist, but plist file is not creating.
I have logged file path and dictionary contents but all these have data still plist not creating
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self sideMenu:#"ML"];
return YES;
}
this will call following method
-(void)sideMenu:(NSString *)title{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"data=%#&deviceid=e8ef8c98262185ec",title];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:SIDE_MENU]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];
NSArray *myArray = [responseString componentsSeparatedByString:#"<!DOC"];
//NSLog(#"%#",myArray);
if (myArray != nil || [myArray count] > 0) {
NSData *data = [[[myArray objectAtIndex:0]stringByReplacingOccurrencesOfString:#"\n" withString:#""] dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self sideMenuFile:title :json];
}
}
-(NSString *)sideMenuFile:(NSString *)titleName :(NSDictionary *)dict{
NSString *filePath;
MyManager *sharedManager =[MyManager sharedManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([titleName isEqualToString:#"ML"])
{ sharedManager.sideMenu = [[NSDictionary alloc]init];
sharedManager.sideMenu = dict;
filePath = [documentsDirectory stringByAppendingPathComponent:#"ML.plist"];
}else if ([titleName isEqualToString:#"HM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"HM.plist"];
}else if ([titleName isEqualToString:#"PDC"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"PDC.plist"];
}else if ([titleName isEqualToString:#"SM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"SM.plist"];
}else if ([titleName isEqualToString:#"GL"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}else if ([titleName isEqualToString:#"CU"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"CU.plist"];
}else if ([titleName isEqualToString:#"BR"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}
NSLog(#"%#",filePath); //printing path
[dict writeToFile:filePath atomically:YES];
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *plistName = #"GL";
NSString *finalPath = [basePath stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName]];
NSDictionary *dictww=[[NSDictionary alloc]initWithContentsOfFile:finalPath];
NSLog(#"dict%#",dictww); //printing nill
return filePath;
}
JSON file structure
{
sigallery = {
rows = (
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/1.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 1;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
},
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/2.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 2;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
}
)
}
}
Your code makes a number of non-optimal assumptions.
1)
Whenever you write out a file, you should always check for any error condition if it's available. NSDictionary's writeTo... methods do return Booleans whether the file has been written out or not, so you could do:
NSLog(#"%#",filePath); //printing path
BOOL success = [dict writeToFile:filePath atomically:YES];
if (success == false)
{
NSLog(#"did not successfully write dictionary to path %#", filePath);
} else {
// ... do everything else in here
}
2)
You write out files wih the format titleName + GL | PDC | SM.plist but when you try to read things back in, there is no titleName as part of the finalPath, so nothing lines up here.
3)
Also, why do you assume basePath is valid (it looks like it could be nil)?
My APP gets a JSON string from a api call JSON string has objects and a array in it. This is what i have done so far but i couldn't get the values from it . advice me please and I'm new to iOS .This is my JSON String :
{
"Id":"0d95a9f6-c763-4a31-ac6c-e22be9832c83",
"Name":"john",
"ProjectName":"project1",
"StartDate":"\/Date(1447200000000)\/",
"Documents":
[{
"Id":"2222a","Name":"book1","ContentType":"application/pdf"
},
{
"Id":"3718e","Name":"Toolbox","ContentType":"application/fillform"
}]
}
Code
NSString *URLString = [NSString stringWithFormat:#"http://mysite/API/Assignments?"];
NSURL *url = [NSURL URLWithString:URLString];
NSData *data=[NSData dataWithContentsOfURL:url];
json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
assignArray=[[NSMutableArray alloc]init];
for (int i=0; i<json.count; i++) {
NSString *aID=[[json objectAtIndex:i]objectForKey:#"Id"];
NSString *uName=[[json objectAtIndex:i]objectForKey:#"Name"];
NSString *pName=[[json objectAtIndex:i]objectForKey:#"ProjectName"];
//[self initwithUserID:uID userName:uName proName:pName];
// [self retrieveAssignmentDetails:aID];
AssignmentsJson *assignment=[[AssignmentsJson alloc]initwithassignID:aID userName:uName proName:pName];
[assignArray addObject:assignment];
your json is not array so parse like following
NSString *aID = json[#"Id"];
NSString *uName = json[#"Name"];
NSString *pName = json[#"ProjectName"];
NSString *startDate = json[#"StartDate"];
NSArray *documents = json[#"Documents"];
for (NSDictionary *item in documents) {
NSString *itemID = item[#"Id"];
NSString *itemName = item[#"Name"];
NSString *itemContentType = item[#"ContentType"];
}
Your Json Object is NSDictionary. so you can directly get data using valueForKey
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSString *aID = json[#"Id"];
NSString *uName = json[#"Name"];
NSString *pName = json[#"ProjectName"];
for Id,Name and ContentType is inside your array object within your NSDictionary object.
so you can get those values accessing array index.
NSArray *arr = json[#"Documents"];
for (int i=0; i<arr.count; i++) {
NSString *aID=[[arr objectAtIndex:i]objectForKey:#"Id"];
NSString *uName=[[arr objectAtIndex:i]objectForKey:#"Name"];
NSString *cType=[[arr objectAtIndex:i]objectForKey:#"ContentType"];
}
You should learn NSArray and NSDictionary Structure first. it will help you in future. Hope this will help you.
you can do it by following way.
Your Json is in NSDictionary format.
NSData * data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://mysite/API/Assignments?"]];
NSDictionary * dicResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if(dicResponse){
NSString * strID = [dicResponse valueForKey:#"Id"];
NSString * strName = [dicResponse valueForKey:#"Name"];
NSString * strProjectName = [dicResponse valueForKey:#"ProjectName"];
NSString * strDate = [dicResponse valueForKey:#"StartDate"];
NSArray * arrDocuments = [NSArray arrayWithArray:[dicResponse valueForKey:#"Documents"]];
for (int i=0; i< arrDocuments.count; i++) {
NSString * ID=[[arrDocuments objectAtIndex:i]valueForKey:#"Id"];
NSString * Name=[[arrDocuments objectAtIndex:i]valueForKey:#"Name"];
NSString * Type=[[arrDocuments objectAtIndex:i]valueForKey:#"ContentType"];
}
}
I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}
Okay stupid question, this should be obvious but all my googling didn't do nothing.
I've met these two methods:
myarray/dictionary = [jsonDictionary objectForKey:#"ID"];
This gets the pair for the key ID
myarray/dictionary = jsonDictionary[#"COMMON"];
This omits the data within COMMON
This is my dictionary from json, how do I get an array of all the ID keys?
{
COMMON = {
CATEGORY = computing;
"NUM_PER_PAGE" = 0;
"PAGE_NO" = 0;
"REQUEST_DATE" = 201410271757;
"RESULT_CD" = 0000;
"RESULT_MSG" = SUCCESS;
"SVC_ID" = 7;
TARGET = "list(VM)";
};
DATA = {
"VM_LIST" = (
{
"#SVC_ID" = 7;
ID = VMSPE0000000083;
"MACHIN_STATUS_DESC" = "[150748]success:virtual machine power on";
"MEM_SIZE_MB" = 1024;
"OS_NAME" = "CentOS_6.4_en_64";
"PURPOSE_NM" = "Service_Default";
"SERVER_STATUS_MSG" = "VM running";
"USVC_DESC" = "7/Running, No Change r/hurhurhur, Inc.";
"VCPU_CNT" = 2;
"VIRT_TYPE_DESC" = "Para Virtualization";
"VM_ALIAS" = CV00900000083;
"VM_OPER_DESC" = "Power On";
"VNIC_CNT" = 1;
},
{
"#SVC_ID" = 7;
ID = VMSPE0000000093;
"MACHIN_STATUS_DESC" = "[150749]success:virtual machine reboot";
"MEM_SIZE_MB" = 2048;
"OS_NAME" = "Gentoo _2011-0 _en_64";
"PURPOSE_NM" = "Service_Default";
"SERVER_STATUS_MSG" = "VM running";
"USVC_DESC" = "7/Running, No Change r/hurhurhur, Inc.";
"VCPU_CNT" = 1;
"VIRT_TYPE_DESC" = "Para Virtualization";
"VM_ALIAS" = CV00900000093;
"VM_OPER_DESC" = Reboot;
"VNIC_CNT" = 1;
},
{
"#SVC_ID" = 7;
ID = VMSPE0000000096;
"MACHIN_STATUS_DESC" = "[163023]success:virtual machine running";
"MEM_SIZE_MB" = 1024;
"OS_NAME" = "OpenSuse_12.1_en_64";
"PURPOSE_NM" = "Service_Default";
"SERVER_STATUS_MSG" = "VM running";
"USVC_DESC" = "7/Running, No Change r/hurhurhur, Inc.";
"VCPU_CNT" = 2;
"VIRT_TYPE_DESC" = "Para Virtualization";
"VM_ALIAS" = CV00900000096;
"VM_OPER_DESC" = "Vm Initialization";
"VNIC_CNT" = 1;
}
);
};
}
The proper output for the array would be
#"VMSPE0000000083", #"VMSPE0000000093", #"VMSPE0000000096"
I can't seem to figure it out, the nesting confuses me.
This is the answer for directly getting values of response in array
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://http://stackoverflow.com/questions/26587283/parse-json-dictionary-array-within-arrays-get-objects-for-key-in-deeper-nests/26589961#26589961"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
//step by step getting values from Array[copy the Dictionary values to Array] format
NSMutableArray *array = [[jsonArray objectForKey:#"COMMON"] mutableCopy];
NSString *strCAT = [NSString stringWithFormat:#"%#",[array valueForKey:#"CATEGORY"]];
NSString *strNUM = [NSString stringWithFormat:#"%#",[array valueForKey:#"NUM_PER_PAGE"]];
NSString *strPAGE = [NSString stringWithFormat:#"%#",[array valueForKey:#"PAGE_NO"]];
NSString *strREQUEST = [NSString stringWithFormat:#"%#",[array valueForKey:#"REQUEST_DATE"]];
NSString *strRESULT = [NSString stringWithFormat:#"%#",[array valueForKey:#"RESULT_CD"]];
NSString *strRESULT_MS = [NSString stringWithFormat:#"%#",[array valueForKey:#"RESULT_MSG"]];
NSString *strSVC = [NSString stringWithFormat:#"%#",[array valueForKey:#"SVC_ID"]];
NSString *strTAR = [NSString stringWithFormat:#"%#",[array valueForKey:#"TARGET"]];
//Getting values from Mutiple Dictionary of Array inside the Dictionary.We are going to have all values of SVC_ID,ID,MACHIN_STATUS_DESC,MEM_SIZE_MB,OS_NAME,PURPOSE_NM,SERVER_STATUS_MSG,USVC_DESC,VCPU_CNT,VM_ALIAS,VIRT_TYPE_DESC,VM_OPER_DESC,VNIC_CNT in seperate Array directly using valueForKeyPath.
NSDictionary *dictValue = [jsonArray valueForKey:#"DATA"];
NSMutableArray *arraySVC_ID = [dictValue valueForKeyPath:#"VM_LIST.#SVC_ID"];
NSMutableArray *arrayID = [dictValue valueForKeyPath:#"VM_LIST.ID"];
NSMutableArray *arrayMACHIN_STATUS_DESC = [dictValue valueForKeyPath:#"VM_LIST.MACHIN_STATUS_DESC"];
NSMutableArray *arrayMEM_SIZE_MB = [dictValue valueForKeyPath:#"VM_LIST.MEM_SIZE_MB"];
NSMutableArray *arrayOS_NAME = [dictValue valueForKeyPath:#"VM_LIST.OS_NAME"];
NSMutableArray *arrayPURPOSE_NM = [dictValue valueForKeyPath:#"VM_LIST.PURPOSE_NM"];
NSMutableArray *arraySERVER_STATUS_MSG = [dictValue valueForKeyPath:#"VM_LIST.SERVER_STATUS_MSG"];
NSMutableArray *arrayUSVC_DESC = [dictValue valueForKeyPath:#"VM_LIST.USVC_DESC"];
NSMutableArray *arrayVCPU_CNT = [dictValue valueForKeyPath:#"VM_LIST.VCPU_CNT"];
NSMutableArray *arrayVM_ALIAS = [dictValue valueForKeyPath:#"VM_LIST.VM_ALIAS"];
NSMutableArray *arrayVIRT_TYPE_DESC = [dictValue valueForKeyPath:#"VM_LIST.VIRT_TYPE_DESC"];
NSMutableArray *arrayVM_OPER_DESC = [dictValue valueForKeyPath:#"VM_LIST.VM_OPER_DESC"];
NSMutableArray *arrayVNIC_CNT = [dictValue valueForKeyPath:#"VM_LIST.VNIC_CNT"];
If what you posted is your JSON data, and you have it all in an NSDictionary* jsonDict, then
NSDictionary* commonDict = jsonDict [#"COMMON];
NSString* category = commonDict [#"CATEGORY"];
NSDictionary* dataDict = jsonDict [#"DATA];
NSArray* vmList = dataDict [#"VM_LIST"];
NSDictionary* firstVM = vmList [0];
NSString* firstVMID = firstVM [#"ID"];
I will solve your problem very simply.Please just follow the following steps
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
//Step by Step getting values from Dictionary Format
NSString *strCATEGORY = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"CATEGORY"]];
NSString *strNUM_PER_PAGE = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"NUM_PER_PAGE"]];
NSString *strPAGE_NO = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"PAGE_NO"]];
NSString *strREQUEST_DATE = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"REQUEST_DATE"]];
NSString *strRESULT_CD = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"RESULT_CD"]];
NSString *strRESULT_MSG = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"RESULT_MSG"]];
NSString *strSVC_ID = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"SVC_ID"]];
NSString *strTARGET = [NSString stringWithFormat:#"%#",[[jsonArray valueForKey:#"COMMON"]valueForKey:#"TARGET"]];
NSMutableArray *arrayDict = [[jsonArray valueForKey:#"DATA"]valueForKey:#"VM_LIST"];
for(int i=0;i<[arrayDict count];i++)
{
NSString *strSVC_ID = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"#SVC_ID"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"ID"]];
NSString *strMACHIN_STATUS_DESC = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"MACHIN_STATUS_DESC"]];
NSString *strMEM_SIZE_MB = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"MEM_SIZE_MB"]];
NSString *strOS_NAME = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"OS_NAME"]];
NSString *strPURPOSE_NM = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"PURPOSE_NM"]];
NSString *strSERVER_STATUS_MSG = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"SERVER_STATUS_MSG"]];
NSString *strUSVC_DESC = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"USVC_DESC"]];
NSString *strVCPU_CNT = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"VCPU_CNT"]];
NSString *strVM_ALIAS = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"VM_ALIAS"]];
NSString *strVIRT_TYPE_DESC = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"VIRT_TYPE_DESC"]];
NSString *strVM_OPER_DESC = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"VM_OPER_DESC"]];
NSString *strVNIC_CNT = [NSString stringWithFormat:#"%#",[[arrayDict objectAtIndex:i]valueForKey:#"VNIC_CNT"]];
}}
Once you get to the array that's the value of the key, "VM_LIST", you can use valueForKey (which uses Key-Value coding) to get the array of all the values of the "ID" key. To get to that array just work your way down -- objectForKey:#"Data" gets you to a dictionary with one key, "VM_LIST". Using objectForKey:"VM_LIST" on that dictionary gets you to the array you're interested in. So, all you need is,
NSArray *array = [jsonDict[#"DATA"]["VM_LIST"] valueForKey:#"ID"];
jsonDict is the dictionary that you logged out in your question.
I want to get tweets with a specific hashtag. I use the Twitter search URL. This is my code:
NSMutableString *urlString = [NSMutableString stringWithFormat:#"%s","http://search.twitter.com/search.json?q=%23zesdaagsegent"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
NSError *error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", json);
NSMutableArray *results =[NSMutableArray array];
for(NSDictionary *item in json)
{
[results addObject:[item objectForKey:#"results"]];
}
My NSLog gets me the output I need:
2013-05-28 09:48:45.080 ZesdaagseGent[572:11303] {
"completed_in" = "0.023";
"max_id" = 339031661368975360;
"max_id_str" = 339031661368975360;
page = 1;
query = "%23zesdaagsegent";
"refresh_url" = "?since_id=339031661368975360&q=%23zesdaagsegent";
results = (
{
"created_at" = "Mon, 27 May 2013 14:53:41 +0000";
"from_user" = SigfridMaenhout;
"from_user_id" = 369194526;
"from_user_id_str" = 369194526;
"from_user_name" = "Sigfrid Maenhout";
geo = "";
id = 339031661368975360;
"id_str" = 339031661368975360;
"iso_language_code" = nl;
metadata = {
"result_type" = recent;
};
source = "<a href="http://twitter.com/">web</a>";
text = "#zesdaagsegent Het is een zonnige dag hier in Merelbeke. We verlangen allemaal naar een beetje zonnestralen in het
gezicht, toch?";
}
);
"results_per_page" = 15;
"since_id" = 0;
"since_id_str" = 0; }
I need the array "results" with the objects in. My problem is that I can't get the results in an NSMutableArray with the method objectForKey.
Does anyone has an idea?
Try this :
NSMutableArray *results = [NSMutableArray array];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
for (NSDictionary *result in jsonResponse[#"results"]) {
[results addObject:result];
}
And you should have a NSArray results containing X NSDictionary for each of the matching tweets.
PS : [#"results"] is the modern Objective-C syntax for [NSDictionary objectForKey:#"results"]