Parsing multiple row from json info in objective-c - objective-c

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]);
}
}

Related

append values for key NSMutableDirectory

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?

Get all keys of a multidimensional dictionary

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.

Parse NSDictionary in NSArray created from JSON in Objective-C

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
}

objective-c: read an array create by json

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.

Getting values when NSDictionary contains a list

I am being passed a dictionary:
aDictionary
When I log it out the dictionary has the following format:
{
value1 = "subValue1 {label=value1, info1=, info2=}";
value2 = "subValue2 {label=value2, info1=, info2=}";
value3 = "subValue3 {label=value2, info1=, info2=}";
}
I need to iterate over the dictionary and then determine if there is a value for value3 -> subValue3 -> info2.
I can do the initial iteration and I can make a subdictionary of the line:
"subValue3 {label=value2, info1=, info2=}"
But when I try to use it, say to get a count of the keys, I get -[subValue3 allKeys]: unrecognized selector sent to instance.
NSArray *keys;
int i, count;
id key, value;
keys = [aDictionary allKeys];
count = [keys count];
for (i = 0; i < count; i++)
{
key = [keys objectAtIndex:i];
value = [aDictionary objectForKey:key];
NSLog (#"Key: %# for value: %#", key, value);
NSDictionary *subDictionary = [aDictionary objectForKey:key];
if ([key isEqualToString:#"info2"]) {
DLog(#"subDictioanry = %#", subDictionary);
// Everything is fine up to here
NSArray *keys2;
int i2, count2;
id key2, value2;
keys2 = [subDictionary allKeys];
count = [keys2 count];
//
// Right here I get "-[subValue3 allKeys]: unrecognized selector sent to instance"
//
for (i2 = 0; i2 < count2; i2++) {
key2 = [keys2 objectAtIndex:i2];
value = [subDictionary objectForKey:key];
DLog (#"Key: %# for value: %#", key2, value2);
NSDictionary *subDictionary2 = [subDictionary objectForKey:key2];
DLog(#"subDictionary2 = %#", subDictionary2);
}
}
Questions:
I am not sure what the format of that second group of values is ("subValue3 {label=value2, info1=, info2=}"). Is it a set, an array, a dictionary?
How do I get that group into a dictionary (without failing on the key(?) "subValue3") so that I can check if the key info2 has any value?
Disclaimers:
I know there are more efficient ways to iterate over a dictionary, I'm just trying to be as clear as possible.
I'm sure there is just something basic I'm missing but I am not seeing the answer in the Apple docs on iteration or NSDictionary nor am I finding anything about the format in that second group.
Thanks!
right now "subValue1 {label=value1, info1=, info2=}"; is a NSString. So allKeys of a NSString will crash.
Infact does this "subValue1 {label=value1, info1=, info2=}"; look like a valid json. I dont think this is a valid JSON. Even jsonlint.com thinks so.
This is a valid json
{
"subValue1": {
"label": "value1",
"info1": "",
"info2": ""
}
}
After you construct json like so, then use NSJSONSerialization to convert -
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &e];
if (!jsonDict)
{
NSLog(#"Error parsing JSON: %#", e);
} else
{
for(NSDictionary *item in jsonDict)
NSLog(#"Item: %#", item);
}