Parsing Vimeo Json response in ios - ios

I got this json response
{
"generated_in" = "0.0283";
stat = ok;
videos = {
"on_this_page" = 3;
page = 1;
perpage = 50;
total = 3;
video = (
{
"embed_privacy" = anywhere;
id = 73198189;
"is_hd" = 1;
"is_watchlater" = 0;
license = 0;
"modified_date" = "2013-08-27 01:29:16";
owner = 20303618;
privacy = anybody;
title = Untitled;
"upload_date" = "2013-08-27 00:57:36";
},
{
"embed_privacy" = anywhere;
id = 73197989;
"is_hd" = 0;
"is_watchlater" = 0;
license = 0;
"modified_date" = "2013-08-27 01:24:17";
owner = 20303618;
privacy = anybody;
title = sample2;
"upload_date" = "2013-08-27 00:52:40";
},
{
"embed_privacy" = anywhere;
id = 72961770;
"is_hd" = 0;
"is_watchlater" = 0;
license = 0;
"modified_date" = "2013-08-23 05:57:48";
owner = 20303618;
privacy = anybody;
title = sample;
"upload_date" = "2013-08-23 05:25:44";
}
);
};
}
when i am trying to parse it for the video id.
The technique i used is
i converted that json into NSDictionary jsondata and
NSString *videoid = [[[jsondata objectForKey:#"videos"]valueForKey:#"video"]valueForKey:#"id"];
NSLog(#"video string is %#",videoid);
the result is:
(
73198189,
73197989,
72961770
)
but i am not able to access the normal string functions on that string to retrieve the id's.
it is saying an error unrecognized selector was sent.
Is there a better way to parse that string, i tried google but every post says the same approach.

You not getting a string but an array of strings, the JSON response holds mutiple videos. The code you used will retrieve all the id of all the videos.
You can loop thru the found videos like:
NSArray *videoIdArray = [jsondata valueForKeyPath:#"videos.video.id"];
for(NSString *videoId in videoIdArray) {
NSLog(#"video string is %#",videoId);
}

Related

Manipulating NSDictionary data

I've managed to export the below data, multiplied by several hundred, into an NSDictionary. I now need to build out a way to put this data into Tinder style app. Can anyone advise how I can get my app to pull out the data against Key "Title" for various indexes. Currently it pulls out 45 records of data containing that one Title as there are 45 keys in my data set.
{
AttachmentFiles = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/AttachmentFiles";
};
};
Attachments = 0;
AuthorId = 22;
AverageRating = "<null>";
BestAnswerId = "<null>";
Body = "We need to think xyz";
CategoriesLookupId = 16;
Community = "<null>";
ContentType = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/ContentType";
};
};
ContentTypeId = 0x01200200C5BB1FEE2601B9439CD527C288D85A7B;
Created = "2014-03-21T08:37:33Z";
DescendantLikesCount = 8;
DescendantRatingsCount = "<null>";
DiscussionLastUpdated = "2014-06-19T12:57:58Z";
EditorId = 96;
EmailSender = "<null>";
FieldValuesAsHtml = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/FieldValuesAsHtml";
};
};
FieldValuesAsText = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/FieldValuesAsText";
};
};
FieldValuesForEdit = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/FieldValuesForEdit";
};
};
File = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/File";
};
};
FileSystemObjectType = 1;
FilterCategory = "<null>";
FirstUniqueAncestorSecurableObject = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/FirstUniqueAncestorSecurableObject";
};
};
Folder = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/Folder";
};
};
GUID = "28144fd4-84b0-434b-9e99-01d939e6a773";
Has20likes = "<null>";
ID = 3;
Id = 3;
IsFeatured = 0;
IsIdeaCreated = "<null>";
IsQuestion = 0;
LastReplyById = 49;
LikesCount = 5;
MemberLookupId = 7;
Modified = "2015-03-11T15:25:20Z";
"OData__UIVersionString" = "2.0";
ParentItemEditorId = "<null>";
ParentItemID = "<null>";
ParentList = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/ParentList";
};
};
Popularity = "7.23632608186099";
RatingCount = "<null>";
RoleAssignments = {
"__deferred" = {
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)/RoleAssignments";
};
};
StepChangePillar = "<null>";
Title = "JIRA Governance";
"__metadata" = {
etag = "\"14\"";
id = "Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)";
type = "SP.Data.Community_x0020_DiscussionListItem";
uri = "https://xxxxxxx/_api/Web/Lists(guid'1594ea5e-0ca7-4de3-81aa-4082bde336a4')/Items(3)";
};
},
Thanks
You should have an array of dictionaries correct?
If so this should work:
NSInteger index = 0; //You can set this to the current page of your scroll view
NSArray * items = /* YOUR ARRAY OF DICTIONARIES */;
NSDictionary * dict = [items objectAtIndex:index];
NSString * title = [dict objectForKey:#"Title"];
You might also consider making a subclass of NSObject and building in a parser for your dictionary so you can access the variables with strong types.

how to store that json data into array, after using jsonserialization iam getting that data

let jsonResult1:NSDictionary = NSJSONSerialization.JSONObjectWithData(da!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
println(jsonResult1)
getting below data in console
{
0 = {
"consulting_dr" = "DR.Appaji .";
"current_bed_nr" = 0;
"current_room_nr" = 0;
"discharge_date" = "03/03/2015 00:00";
"encounter_date" = "02/03/2015 12:45";
"encounter_nr" = 201503024000;
info = "";
"item_description" = "";
name = "Mrs. mythily S";
pdob = "01/08/1976";
pid = 100004;
psex = f;
pyear = "38 Years";
};
1 = {
dosage = 1;
drdate = "25/08/2014";
drnotes = "";
drugclass = Tablet;
duration = "5 day";
frequency = "";
medicine = "ACECLOFENAC+PARACETAMOL";
route = Oral;
tcomplients = "";
};
2 = {
BMI = "A:1:{s:4:\"SPO2\";s:1:\"1\";}";
BSA = "A:1:{s:4:\"SPO2\";s:1:\"1\";}";
"Dystolic_bp" = 29;
Height = 24;
Pulse = 26;
Respiration = 27;
"Systolic_bp" = 28;
Temp = 25;
Weight = 22;
dosage = 1;
drdate = "25/08/2014";
drnotes = "";
drugclass = Tablet;
duration = "5 day";
frequency = "";
medicine = RABEPRAZOLE;
route = Oral;
tcomplients = "";
};
}
how to store this in array
That is a Dictionary. It is easy to get just the data without the keys.
In Objective-C it would be :
NSArray *allData = [jsonResult1 allValues];
For swift it should be like: (not sure about syntax)
var allData = jsonResult1.allValues()
If you're up for it, you should give SwiftyJSON a try.
https://github.com/SwiftyJSON/SwiftyJSON
I've recently used it for an application that deals with a ton of JSON responses from a web service and SwiftyJSON has made it super easy for me to deal with JSON data in Swift. It will convert NSData to Dictionaries or Arrays seamlessly for you.

Access Nested NSDictionary Items

I have this NSDictionary that i received from an api call:
{
items = (
{
accessInfo = {
accessViewStatus = SAMPLE;
country = US;
embeddable = 1;
epub = {
isAvailable = 0;
};
pdf = {
isAvailable = 0;
};
publicDomain = 0;
quoteSharingAllowed = 0;
textToSpeechPermission = ALLOWED;
viewability = PARTIAL;
webReaderLink = "http://books.google.com/books/reader?id=LdB2_WzYpKgC&hl=&printsec=frontcover&output=reader&source=gbs_api";
};
etag = 1xxAlevFUSc;
id = "LdB2_WzYpKgC";
kind = "books#volume";
saleInfo = {
country = US;
isEbook = 0;
saleability = "NOT_FOR_SALE";
};
searchInfo = {
textSnippet = "The saga of their daily exploits won cartoonist Bill Watterson the coveted Reuben Award for "Outstanding Cartoonist of the Year." Something Under the Bed Is Drooling is a jewel.";
};
selfLink = "https://www.googleapis.com/books/v1/volumes/LdB2_WzYpKgC";
volumeInfo = {
authors = (
"Bill Watterson"
);
averageRating = "4.5";
canonicalVolumeLink = "http://books.google.com/books/about/Something_Under_the_Bed_Is_Drooling.html?hl=&id=LdB2_WzYpKgC";
categories = (
Humor
);
contentVersion = "0.0.1.0.preview.1";
description = "\"Be good to yourself: Buy a copy of this Calvin and Hobbes cartoon book. If you don't laugh out loud at every third strip, check your pulse. You may be dead.\" --Phil Musick, Pittsburgh Press Calvin is a rambunctious six-year-old whose manic antics threaten world peace. Hobbes is his stuffed tiger who comes alive when adults aren\"t around. The saga of their daily exploits won cartoonist Bill Watterson the coveted Reuben Award for \"Outstanding Cartoonist of the Year.\" Something Under the Bed Is Drooling is a jewel.";
imageLinks = {
smallThumbnail = "http://bks8.books.google.com/books?id=LdB2_WzYpKgC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api";
thumbnail = "http://bks8.books.google.com/books?id=LdB2_WzYpKgC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api";
};
industryIdentifiers = (
{
identifier = 0836218256;
type = "ISBN_10";
},
{
identifier = 9780836218251;
type = "ISBN_13";
}
);
infoLink = "http://books.google.com/books?id=LdB2_WzYpKgC&dq=isbn:0836218256&hl=&source=gbs_api";
language = en;
pageCount = 127;
previewLink = "http://books.google.com/books?id=LdB2_WzYpKgC&printsec=frontcover&dq=isbn:0836218256&hl=&cd=1&source=gbs_api";
printType = BOOK;
publishedDate = "1988-01-01";
publisher = "Andrews McMeel Publishing";
ratingsCount = 18;
readingModes = {
image = 1;
text = 0;
};
title = "Something Under the Bed Is Drooling";
};
}
);
kind = "books#volumes";
totalItems = 1;
}
What I want to do is create an object from the items in this dictionary. This method needs to work generically for all books without crashing. Even if they are missing some of the attributes. The attributes I need to extract are:
-authors last name (Need for every author listed if there is more than one)
-authors first name (Need for every author listed if there is more than one)
-title
-description
-smallThumbnail
-thumbnail
-isbn_10 identifier
-category
From these I am going to create a "book" object. i will also create an NSSet of Authors, and each Author has a lastName and firstName
How do I go about doing this?
You should be able to safely use NSDictionary's -valueForKeyPath: to retrieve each value from an item dict:
NSArray *names = [itemDict valueForKeyPath:#"volumeInfo.authors"];
NSString *title = [itemDict valueForKeyPath:#"volumeInfo.title"];
...

NSDictionary array of same key

I'm requesting a SOAP Webservice and I parse the response to a NSDictionary. The XML response has multiple unique keys. Here's an example (already parse on the dictionary):
"typ:partits" = {
"typ:dadesPartit" = {
"typ:aforament" = 1;
"typ:codiEsdeveniment" = 2;
"typ:competicio" = GAMPER;
"typ:dataHoraConfirmada" = false;
"typ:dataPartit" = "08/18/14";
"typ:descripcioPartit" = "FCBARCELONA - CLUB LEON F.C.";
"typ:horaPartit" = "9:30:00 PM";
"typ:jornada" = 99;
"typ:partitActiuMenor" = true;
"typ:temporada" = "2014-2015";
"typ:tipusEsdeveniment" = 0;
},
"typ:dadesPartit" = {
"typ:aforament" = 1;
"typ:codiEsdeveniment" = 2;
"typ:competicio" = GAMPER;
"typ:dataHoraConfirmada" = false;
"typ:dataPartit" = "08/26/14";
"typ:descripcioPartit" = "FCBARCELONA - REAL MADRID";
"typ:horaPartit" = "9:30:00 PM";
"typ:jornada" = 101;
"typ:partitActiuMenor" = true;
"typ:temporada" = "2014-2015";
"typ:tipusEsdeveniment" = 0;
};
};
How can I iterate through these keys?, they are the same :( ...
I tried with "allObjects" but when I receive only one "typ:dadesPartit" object it treats it like an array instead of a NSDictionary.
it is returning one type as both your keys are same,
Try renaming the keys to separate names, and the values associated with those keys will come when u type allKeys

iOS - How to parse Json array in xcode and save results are strings

Hi I am trying to parse a Json string as an NSArray and save certain results as strings to set permissions for different users in my app. My current code is:
NSError *jsonParsingError1 = nil;
accountData = [NSJSONSerialization JSONObjectWithData:jsonAccount
options:NSJSONReadingMutableContainers error:&jsonParsingError1];
accountData is an NSMutableArray created in the .h file.
jsonAccount is NSData created by converted an NSString
The NSLog out put for the array is;
{
account = "XXXX";
companyName = XXXXX;
id = XXXXX;
websites = (
{
account = "XXXXX";
accountId = XXXXX;
anonymiseIP = 0;
companyName = XXXXX;
XXXX = 0;
domains = (
"XXXXX"
);
features = {
advancedSegmentation = 1;
attentionHeatmaps = 1;
domains = 0;
dotHeatmaps = 1;
goalConversionTracking = 1;
interactionHeatmaps = 1;
leadInfo = 0;
scrollHeatmaps = 1;
timeHeatmaps = 1;
users = 0;
valueHeatmaps = 1;
visitorPlayback = 1;
visitorScoring = 1;
visitors = 1;
};
fixedElementSelector = "";
flagClicksReceived = 0;
flagDataReceived = 0;
flagGoalsReceived = 0;
flagInteractionsReceived = 0;
flagScrollsReceived = 0;
id = XXXXX;
interactionSelector = "";
name = "XXXX";
permissions = (
segments,
heatmaps,
visitors,
campaigns,
support,
globalSettings,
websiteSettings
);
setCookies = 1;
status = 1;
statusMessage = "";
statusString = OK;
trialling = 1;
}
);
},
When I try and create a sting from one of the results and display it in the log I get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray:]: unrecognized selector sent to instance 0x6a950f0'
How can I save different keys as strings?
Looks like that your JSON is a Dictionary, not an Array.
Your JSON is not array you should parse it like NSDictionary
After parsing the JSON, you should test what kind of object it returned. E.g.:
if ([accountData isKindOfClass:[NSArray class]]) {
// handle like an array
} else if ([accountData isKindOfClass:[NSDictionary class]]) {
// handle like a dictionary
}
Your JSON is a dictionary with four keys: account, companyName, id, and websites.
The key "websites" will give you an array.
You can iterate through the "websites" array, and each element is a dictionary.
Each of the dictionaries in the "websites" array has lots of keys like account, accountId, anonymiseIP and so on. Some of these keys have values that are dictionaries or arrays.
In the NSLog statement, (a, b, c) would be an array, while { a = x; b = y; c = z; } would be a dictionary.
Your server response is a dictionary so change accountData to dictionary
Write NSLog for below and you will get information in it
[accountData objectForKey:#"account"];
[accountData objectForKey:#"companyName"];
[accountData objectForKey:#"id"];
[[accountData objectForKey:#"websites"] count];//array
[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"account"];
[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"];
[[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"]count]; //array
[[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"]objectAtIndex:0];

Resources