I'm trying to get information out of this Dictionary that was created from a JSON string. The JSON string is returned from the server and is put in a dictionary. That dictionary is passed to myMethod that is suppose to break it down so I can get the information that each record contains.
The "Recordset" is an Array. The Record is also an array of dictionaries.
How do I get to the dictionaries? I keep getting NSDictionaryM objectAtIndex: unrecognized selector sent to instance
Recordset = (
{
Record = (
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1691;
MODvc50Name = "10/12 Series 2";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1687;
MODvc50Name = "10/4";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1686;
MODvc50Name = "10/6";
},
etc .. etc... ( about 100 records )
Here is what I have
- (void) myMethod : (NSDictionary*) dictionary {
//INITIAL
NSArray * arrRecordSet = [dictionary objectForKey:#"Recordset"];
NSArray * arrRecord = [arrRecordSet objectAtIndex:0];
NSDictionary * theRecord = [NSDictionary dictionaryWithObjects:arrRecord forKeys:[arrRecord objectAtIndex:0]];
for (int i = 0; i < arrRecord.count; i++) {
NSLog(#"MODMAKlMakeKey: %#", [theRecord objectForKey:#"MODMAKlMakeKey"]);
}
}
Try this
NSArray * arrRecord = [arrRecordSet objectForKey:#"Record"];
Try to check first if the return of [dictionary objectForKey:#"Recordset"] is really a dictionary or an array.
To do this:
if([[dictionary objectForKey:#"Recordset"] isKindOfClass:[NSArray class]]) {
//object is array
}
else if ([[dictionary objectForKey:#"Recordset"] isKindOfClass:[NSDictionary class]]) {
//object is dictionary
}
Related
I'm currently working on objective c code where I have an array I'm looping through and based on the outcomes I add a value to a key.
However when needed I want to append the values for a specific key but I have absolutely no clue on how to achieve this with objective c.
I have written an solution for this in swift before but I can't seem to figure out how to apply the same thing in objective c. Here is what I currently have
-(void)makeDirectory:(NSArray*)aList {
NSMutableDictionary *dic = [NSMutableDictionary new];
for (NSDictionary *entry in aList) {
NSString *character = #"";
xbmcMovie *movie = [[xbmcMovie alloc] initWithDictionary:entry];
NSString *name = movie.Title.stripSpecialCharacters.stripArticle.stripSpaces.stripNumber;
character = name.character;
if (![dic objectForKey:character]) {
[dic setObject:movie forKey:character];
}
///[dic ]
}
}
Here is what I did in swift 3.0
func makeDictionary(_ libraryArray: [songsClass])->[String: [songsClass]]{
var dic = [String: [songsClass]]()
for entry in libraryArray {
var character: String = ""
var songName = entry.songName.stripSpecialCharacters().stripArticle().stripSpaces().stripNumber()
guard let char = songName.characters.first?.string() else { return [:] }
character = char
if dic[character] == nil {
dic[character] = [songsClass]()
}
dic[character]!.append(entry)
}
return dic
}
So if I have understood this correctly, your value in the dictionary is an array which contains a movie, and you want to add to this array, so what you need to do is:
NSMutableArray *movieArray = [NSMutableArray new];
[movieArray addObject:movie];
if (![dic objectForKey:character]) {
[dic setObject:movieArray forKey:character];
}
//If you want to add to this array again then you can do
[movieArray addObject:anotherMovie];
//Or if you need to retrieve the array again
movieArray = [dic objectForKey:character];
[movieArray addObject:anotherMovie];
Also your code has
character = name.character;
where name is a NSString?
I have a dictionary like:
{
dataTypes = (
{
dataType = "datatype1";
editable = 1;
maxValue = 300;
minValue = 0;
order = 1;
title = "Title 1";
type = numeric;
units = kg;
},
{
dataType = "datatype 2";
editable = 1;
maxValue = 300;
minValue = 0;
order = 2;
title = "title2";
type = numeric;
units = gm;
},
{
dataType = "datatype3";
editable = 1;
maxValue = 300;
minValue = 20;
order = 3;
title = "title3";
type = numeric;
units = kg;
}
);
name = "Name";
order = 1
title = "Title";
}
I want to get all keys within this dictionary.
I tried [myDict allKeys], however this is returning only four keys: DataTypes, name, order, title.
I want to retrieve all keys: dataType, editable, maxvalue, etc.
Try this.
NSArray *tempArray = [myDict objectForKey:#"dataTypes"];
NSDictionary *tempDictionary = (NSDictionary *)tempArray[0];
[tempDictionary allKeys] will have what you want.
Write this method.
- (NSDictionary *)dictionaryFromArrayWithinDictionary:(NSDictionary *)dictionary withKey:(NSString *)key{
NSArray *tempArray = [dictionary objectForKey:key];
return (NSDictionary *)tempArray[0];
}
This will return the inner dictionary and simply calling `allKeys' on this dictionary, you will get all the keys you want.
You need to recursively walk through your dictionary, and through any arrays the dictionary might contain, and so on. This can be nicely done via a recursiveKeys method added to all objects, which returns an empty array for objects that are not containers, and walks though the container for objects that are containers:
#interface NSObject(MyCategory)
- (NSArray)recursiveKeys;
#end
#implementation NSObject(MyCategory)
- (NSArray)recursiveKeys {
return #[];
}
#end
#implementation NSArrray(MyCategory)
- (NSArray)recursiveKeys {
NSMutableArray *result = [NSMutableArray array];
for (id item in self) {
[result addObjectsFromArray:[item recursiveKeys]];
}
return [result copy]; //return an immutable array
}
#end
#implementation NSSet(MyCategory)
- (NSArray)recursiveKeys {
NSMutableArray *result = [NSMutableArray array];
for (id item in self) {
[result addObjectsFromArray:[item recursiveKeys]];
}
return [result copy]; //return an immutable array
}
#end
#implementation NSDictionary(MyCategory)
- (NSArray)recursiveKeys {
NSMutableArray *result = [self.allKeys mutableCopy];
for (id key in self) {
[result addObjectsFromArray:[self[key] recursiveKeys];
}
return [result copy]; //return an immutable array
}
#end
You can use it like this:
NSArray *keys = myDictionary.recursiveKeys;
Please pardon any syntax errors, I don't have at this time an Xcode in front of me, I simply typed the code here on SO.
I begin in Ios dev and I got some troubles to manipulate an array create by Json :
I call in my app a web Service which return me data :
{evenements =(
({
dateEvenement ={
1 = "01-01-2013";
2 = "02-01-2013";
3 = "03-01-2013";
4 = "04-01-2013";
};
idEvenement = 61;
nbrInvite = 1;
nomEvenement = "My event Name";
nomUtilisateur = "Lucas ";
}
),
);
}
I'm able to get all the values by the following code except for "dateEvenement" :
NSArray *msgList;
msgList = [ jsonResults objectForKey:#"evenements" ];
for (NSDictionary *evenements in msgList) {
for (NSDictionary *evenement in evenements ) {
NSString *idEvenement = [evenement objectForKey:#"idEvenement"];
NSString *nomUtilisateur = [evenement objectForKey:#"nomUtilisateur"];
NSString *nomEvenement = [evenement objectForKey:#"nomEvenement"];
NSString *nbrInvite = [evenement objectForKey:#"nbrInvite"];
NSArray *dates = [ evenement objectForKey:#"dateEvenement" ];
}
}
Can you help me for getting datas of "dateEvenement"
Well in your JSON the dateEvenement isn't an Array but a dictionary:
NSDictionary *dates = [ evenement objectForKey:#"dateEvenement"];
for(NSNumber *key in dates) {
NSString *dateString = [dates objectForKey:key];
NSLog(%# : %#, key, dateString);
}
As declared in your JSON example the key's for the dictionary are numbers, thus you should NSNumber object for the key type.
Perhaps I am over-thinking or confusing myself, but my head is stuck in a loop over this and I cannot break out.
I have a a JSON of the format: (Validated at http://jsonformatter.curiousconcept.com/)
{
id: 1,
sections: "5",
total: "10",
result: {
3: 00PM: [
{
name: "Anurag",
status: "Web"
},
{
name: "Anurag2",
status: "Web2"
}
],
5: 00PM: [
{
name: "Anurag",
status: "Seated"
}
],
6: 00PM: [
{
name: "Anurag4",
status: "Web4"
},
{
name: "Anurag5",
status: "Web5"
},
{
name: "Anurag6",
status: "Web6"
},
{
name: "Anurag7",
status: "Web7"
}
]
}
}
I have this so far:
NSDictionary *dict = [response JSONValue];
NSDictionary *results = [dict objectForKey:#"result"];
NSInteger num_results = [[dict valueForKey:#"total"] intValue];
NSInteger num_sections = [[dict valueForKey:#"sections"] intValue];
NSMutableArray *sections = [[NSMutableArray alloc] initWithCapacity:num_sections];
NSMutableArray *objarr = [[NSMutableArray alloc] initWithCapacity:num_results];
NSMutableArray *obj= [[NSMutableArray alloc] initWithCapacity:num_sections];
NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:num_results];
for (NSString* key in results) {
NSLog(#"Key: %#", key); // prints out 3:00 PM...5:00 PM etc...
[obj addObject:[results objectForKey:key]]; // nested objects within each key are saved in the array
NSLog(#"Object 1: %#", obj);
}
for (int i = 0; i < [obj count]; i++) {
//NSLog(#"Object 2: %#", [obj objectAtIndex:i]);
[temp addObject:[obj objectAtIndex:i]]; // I take each object from previous array and save it in a temp array
for (int i = 0; i < num_results; i++) {
NSLog(#"Object 3: %#", [temp objectAtIndex:i]);
**[objarr addObject:[temp objectAtIndex:i]]; // I want to extract the object within the object but cannot get it to work**
}
}
I am able to make an array of objects within each of the 3 keys inside results. But I am not able to get each of the objects inside them as a separate object and save them in an array.
For example, in an NSArray I have:
Object 3: (
{
name = "Anurag ";
status = Web;
},
{
name = "Anurag ";
status = Web;
}
)
How can I get the two objects inside this object and save them both in an array?
I guess the main issue is I cannot refer to a key name to get the individual object.
You can use the following code,
NSDictionary *json = [response JSONValue];
// Get the objects you want
NSArray *items = [json valueForKeyPath:#"result.6: 00PM"];
This will return an NSArray with the objects for the key 6: 00PM
Please check this link too.
You are redefining int i in your second for loop. Try something like
for(int j = 0; j < num_results; j++)
[temp addObject:[obj objectAtIndex:i]]; // I take each object from previous array and save it in a temp array
This is useless motion. You're effectively just copying the obj array to the temp array -- no value added.
My json stiring is:
{
"locations" :[
{
id = 0;
lat = "41.653048";
long = "-0.880677";
name = "LIMPIA";
},
{
id = 1;
lat = "41.653048";
long = "-0.890677";
name = "LIMPIA2";
}
]
}
Using:
NSDictionary * root = [datos_string1 JSONValue];
NSArray *bares = (NSArray *) [root objectForKey:#"locations"];
for (NSArray * row in bares) {
NSString *barName1 = [bares valueForKey:#"name"];
NSLog(#"%#",barName1);
}
I obtain from NSlog , twice otput
(
LIMPIA,
LIMPIA2
)
So somthing is wrong. I need to estract di single value parameter (lat, lon and nombre) for each item (in order to use in a mapkit app). Could you help me?
I need to estract di single value parameter (lat, lon and nombre) for each item (in order to use in a mapkit app)
If I understand your question correctly, you're trying to access each value in each dictionary in the locations array, is that right?
In order to access each value (if that is indeed your question), this should work:
NSDictionary *root = [datos_string1 JSONValue];
NSArray *bares = (NSArray *)[root objectForKey:#"locations"];
// Each item in the array is a dictionary, not an NSArray
for (NSDictionary *dict in bares) {
// Loop over keys
for (NSString *key in [dict allKeys]) {
NSLog(#"dict[%#] == %#", key, [dict objectForKey:key]);
}
}