Ok I get and store a Json feed to an array called jsonArray. I then loop over the jsonArray pulling out the array keys and storing them as strings. I then add those strings to an inner dictionary called innerDict, I then add that dictionary to the info dictionary with the key thePostCode using the below. So basically innerDict is stored inside infoDict.
-(void)pointInfo{
infoDict = [[NSMutableDictionary alloc]init];
for (int i = 0; i < jsonArray.count; i++) {
innerDict = [[NSMutableDictionary alloc]init];
info = [[jsonArray objectAtIndex:i]objectForKey:#"inf"];
thePostCode = [[jsonArray objectAtIndex:i]objectForKey:#"pc"];
mail = [[jsonArray objectAtIndex:i]objectForKey:#"mail"];
url = [[jsonArray objectAtIndex:i]objectForKey:#"url"];
type = [[jsonArray objectAtIndex:i]objectForKey:#"items"];
[innerDict setObject:type forKey:#"Items"];
[innerDict setObject:info forKey:#"Info"];
[innerDict setObject:mail forKey:#"Mail"];
[innerDict setObject:url forKey:#"Url"];
[infoDict setObject:innerDict forKey:thePostCode];
}
the output of infoDict looks like this:
infoDict is {
"ME14 4NN" = {
Info = "";
Items = 4;
Mail = "";
Url = "";
};
"ME15 6LG" = {
Info = af;
Items = "0,6,9";
Mail = "";
Url = "";
};
"ME15 6YE" = {
Info = "";
Items = "4,5,6,7,11";
Mail = "";
Url = "";
};
}
Now what I want to do is get the values of the innerDict object i.e "ME15 6YE" above and use that as the query to pull out the associated data for Info, Items, Mail and Url keys. I have been staring at my screen for a few hours but I am just not getting it.
I can pull out the last object of the inner dict using the below however I would like to grab all the values associated with a particular postcode which would be the innerDict key. Completely brain fried at the moment!
for (NSMutableDictionary *dictionary in infoDict) {
NSLog(#"URL %#", [innerDict objectForKey:#"Url"]);
NSLog(#"MAIL %#", [innerDict objectForKey:#"Mail"]);
NSLog(#"ITEMS %#", [innerDict objectForKey:#"Items"]);
NSLog(#"ITEMS %#", [innerDict objectForKey:#"Info"]);
}
To get the correct inner dictionary, use objectForKey:
NSDictionary *innerDict = [infoDict objectForKey:#"ME15 6YE"];
NSLog(#"Url %#", [innerDict objectForKey:#"Url"]);
NSLog(#"Mail %#", [innerDict objectForKey:#"Mail"]);
NSLog(#"Items %#", [innerDict objectForKey:#"Items"]);
NSLog(#"Info %#", [innerDict objectForKey:#"Info"]);
Maybe I'm misunderstanding something, but I think this should answer your questions.
You're using dictionary in the for loop, but trying to access it via innerDict. Change it to:
for (NSMutableDictionary *dictionary in infoDict) {
NSLog(#"URL %#", [dictionary objectForKey:#"Url"]);
NSLog(#"MAIL %#", [dictionary objectForKey:#"Mail"]);
NSLog(#"ITEMS %#", [dictionary objectForKey:#"Items"]);
NSLog(#"ITEMS %#", [dictionary objectForKey:#"Info"]);
}
Or, for a single one,
NSMutableDictionary *inner = [infoDict objectForKey:#"POST CODE HERE"];
NSLog(#"URL %#", [inner objectForKey:#"Url"]);
NSLog(#"MAIL %#", [inner objectForKey:#"Mail"]);
NSLog(#"ITEMS %#", [inner objectForKey:#"Items"]);
NSLog(#"ITEMS %#", [inner objectForKey:#"Info"]);
Related
this is my json content.
[
{
"sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
"commit":{
"author":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"committer":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"message":"Merge branch '1.5.x'",
}
}
]
and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.
NSMutableArray *CommitArray = [[NSMutableArray alloc] init];
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
commitDictObj.message = [CommitDictionary objectForKey:#"message"];
for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:#"committer"]) {
Committer *author = [[Committer alloc] init];
author.name = [CommitterDictionary objectForKey:#"name"];
author.email = [CommitterDictionary objectForKey:#"email"];
author.date = [CommitterDictionary objectForKey:#"date"];
}
[CommitArray addObject:commitDictObj];
}
for (int i =0 ; i < [CommitArray count] ; i++){
CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
NSLog(#"Commit Message: %#", commitDictObj.message);
}
return 0;
}
}
i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
With that:
for (NSDictionary *shaCommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:#"commit"];
(1) Convert JSON to NSDictionary
NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
(2) Access the dictionary values (fast enumeration available by now!!
NSString *message = dictionary[#"message"];
NSDictionary *author = dictionary[#"author"];
NSString *name = author[#"author"];
NSString *email = author[#"author"];
NSString *date = author[#"author"];
// OR:
// NSString *name = dictionary[#"author"][#"author"];
// NSString *email = dictionary[#"author"][#"author"];
// NSString *date = dictionary[#"author"][#"author"];
And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016
I have the following object C code for receiving PubNub message.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
NSLog(#"Received message: %# on channel %# at %#", message.data.message,
message.data.subscribedChannel, message.data.timetoken);
}
The returned data is
Received message: (
{
key = userName;
value = Enoch;
},
{
key = photoID;
value = 3;
},
{
key = userID;
value = 1;
},
{
key = actionType;
value = chat;
},
{
key = message;
value = H;
}
) on channel chat at 14888810882049989
I would like to parse the message to a dictionary object for accessing the "value" by using the "key"
I am very new in objective C programming and don't know how to do.
Please help.
Loop through the message array and set the key value in dictionary.
NSArray *array = (NSArray*)message.data.message;
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for (NSDictionary *item in array) {
[dic setObject:[item objectForKey:#"value"] forKey:[item objectForKey:#"key"]];
}
NSLog(#"%#", dic);
Or
NSArray *array = (NSArray*)message.data.message;
NSArray *values = [array valueForKey: #"value"];
NSArray *keys = [array valueForKey: #"key"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSLog(#"%#", dic);
You can use below method for parsing your data and convert it into dictionary
ChatterBoxMessage *chatterBoxMessage = [[ChatterBoxMessage alloc] initFromDictionary: message.data.message withTimeToken: message.data.timetoken];
[chatterBoxMessage asDictionary];
By This method you will get dictionary.
Above ChatterBoxMessage is a PubNub library class.
Also you can parse your data like below :
for (NSDictionary *objectData in message.data.message) {
NSLog(#"Value : %#",objectData[#"value"]);
NSLog(#"Key : %#",objectData[#"key"]);
}
I want to save a Json Object in a field (text) sqlite and then read it again with a select and retransform to NSDictionary or NSMutableArray to parse the key/values
This is how i save actually in the sqlite DB
As you see, is a song object from the iTunes api. I want to read that object and parse it.
This is how i make the select query and save it in a NSDictionary while i filling and NSMutableArary
globals.arrayMyPlaylists = [[NSMutableArray alloc] init];
// Form the query.
NSString *query = #"select * from myplaylists";
// Get the results.
NSArray *listas = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
for (int i = 0; i < listas.count; i++) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSLog(#"lista %d %# %#", i, listas[i][0], listas[i][1]);
[dictionary setObject:listas[i][0] forKey:#"id"];
[dictionary setObject:listas[i][1] forKey:#"nombre"];
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
[dictionary setObject:canciones forKey:#"canciones"];
[globals.arrayMyPlaylists addObject:dictionary];
dictionary = nil;
}
When i try to read it in the cellForRowAtIndexPath method
NSArray *canciones = [[NSArray alloc] initWithArray:[[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"canciones"]];
and try to get the value for the key artworkUrl100
[cell.tapa1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", [[canciones objectAtIndex:i] valueForKey:#"artworkUrl100"]]] placeholderImage:nil];
i get the error
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7ff575810600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key artworkUrl100.'
i understand i'm messing up in some way with dictionarys/nsmutablearrays. I need some help. Thanks!
EDIT: this is how i save the data in the DB
NSString *query = [NSString stringWithFormat:#"insert into canciones (idplaylist, cancion) values ('%#', '%#')", [[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"id"], self.elementoSeleccionado];
[self.dbManager executeQuery:query];
self.elementoSeleccionado is the NSMutableArray with the "cancion" object and it's saved like it's shows the first image.
EDIT 2: this is what i get trying schmidt9's answer
EDIT 3: OK, i have the json string escaped. How i have to parse now?
You should parse your output first with NSJSONSerialization:
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
// I suppose your array canciones should contain only one song object ...
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:canciones[0] options:0 error:&error];
if(error) {
// handle error ...
}
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *result = object;
[dictionary setObject:result forKey:#"canciones"];
}
Edit
Saving to database
2 options:
- if you get a prepared json string, save it directly to DB, but before you should escape quotes. See eg. here
- if you have NSDictionary:
- (NSString*)JSONStringWithDictionary:(NSDictionary*)dictionary prettyPrinted:(BOOL)prettyPrinted
{
NSJSONWritingOptions options = (prettyPrinted) ? NSJSONWritingPrettyPrinted : 0;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:options error:nil];
return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
}
After that you should escape the string too.
I am working on Action Extension Objective C. I have successfully created Extension for share recent contact in my Extension. In that I am getting v Card String. How can I get Mobile Number from v Card String. Any help would be appreciated.
Using contactsWithData:error: class method of CNContactVCardSerialization, you can retrieve info from a vCard.
It's from Contacts.framework, available since iOS9.
For earlier version, you can use AddressBook.framework. You can read info here.
NSError *errorVCF;
NSArray *allContacts = [CNContactVCardSerialization contactsWithData:[contactStr dataUsingEncoding:NSUTF8StringEncoding] error:&errorVCF];
if (!errorVCF)
{
NSMutableString *results = [[NSMutableString alloc] init];
//NSLog(#"AllContacts: %#", allContacts);
for (CNContact *aContact in allContacts)
{
NSArray *phonesNumbers = [aContact phoneNumbers];
for (CNLabeledValue *aValue in phonesNumbers)
{
CNPhoneNumber *phoneNumber = [aValue value];
[results appendFormat:#"%# %#\n", [aValue label], [phoneNumber stringValue]];
}
}
NSLog(#"Final: %#", results);
}
How do i display all data in a UILabel?
I am currently using this :
for (NSManagedObject *obj in matchingData)
{
lastname = [obj valueForKey:#"lastname"];
name = [obj valueForKey:#"name"];
NSLog(#"Name:%#\n Last Name %#\n", [obj valueForKey:#"name"],[obj valueForKey:#"lastname"]);
}
self.displayLabel2.text = [NSString stringWithFormat:#"Guest : %# %#" ,name, lastname];
}
In the console I get all my data but in UILabel (displayLabel2) I just get one name…i just don't get it…
The way that your code reads, on each loop through the obj NSManagedObject, the name and lastname will be reset. So the label will only display the final loop's data.
try creating a string within the loop
NSMutableString *stringText = [NSMutableString string];
for (NSManagedObject *obj in matchingData)
{
lastname = [obj valueForKey:#"lastname"];
name = [obj valueForKey:#"name"];
NSLog(#"Name:%#\n Last Name %#\n", [obj valueForKey:#"name"],[obj valueForKey:#"lastname"]);
stringText = [NSString stringWithFormat:#"%# %#", stringText, [NSString stringWithFormat:#"Guest : %# %#" ,name, lastname]];
}
self.displayLabel2.text = stringText;
}