如何使用多个密钥创建NSDictionary?

我不确定我要问的是实际上是一个带有多个键的NSDictionary但是没问题。

我想要做的是创建一个NSDictionary其中包含我的数据的键和值,然后将其转换为JSON格式。 JSON格式看起来完全像这样:

 { "eventData": { "eventDate": "Jun 13, 2012 12:00:00 AM", "eventLocation": { "latitude": 43.93838383, "longitude": -3.46 }, "text": "hjhj", "imageData": "raw data", "imageFormat": "JPEG", "expirationTime": 1339538400000 }, "type": "ELDIARIOMONTANES", "title": "accIDENTE" } 

我只使用过像这样的NSDictionaries

 NSArray *keys = [NSArray arrayWithObjects:@"eventDate", @"eventLocation", @"latitude" nil]; NSArray *objects = [NSArray arrayWithObjects:@"object1", @"object2", @"object3", nil]; dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

但上述格式并非全部都与关键价值有关。 所以我的问题是NSDictionary如何适应JSON格式? 感谢阅读我的post,对不起,如果有任何困惑。

你知道你可以在另一个NSDictonary拥有一个NSDictionary吗?

 NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:@"43.93838383",@"latitude",@"-3.46",@"latitude", nil]; NSMutableDictionary *eventData = [NSDictionary dictionaryWithObjectsAndKeys:eventLocation,@"eventLocation", nil]; [eventData setObject:@"Jun 13, 2012 12:00:00 AM" forKey:@"eventDate"]; [eventData setObject:@"hjhj" forKey:@"text"]; . . . NSMutableDictionary *finalDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:eventData,@"eventData", nil]; [finalDictionary setObject:@"ELDIARIOMONTANES" forKey:@"type"]; [finalDictionary setObject:@"accIDENTE" forKey:@"title"]; 

现在有了Objective-C文字,有一种更好,更简单,更简洁的方法来实现这一目标。 这是您使用这种新语法的确切字典:

 NSDictionary *dictionary = @{ @"eventData": @{ @"eventDate": @"Jun 13, 2012 12:00:00 AM", @"eventLocation": @{ @"latitude": @43.93838383, @"longitude": @-3.46 }, @"text": @"hjhj", @"imageData": @"raw data", @"imageFormat": @"JPEG", @"expirationTime": @1339538400000 }, @"type": @"ELDIARIOMONTANES", @"title": @"accIDENTE" }; // Prints: "43.93838383" NSLog(@"%@", dictionary[@"eventData"][@"eventLocation"][@"latitude"]); 

如何使用NSDictionary创建NSArray和Access对象?

…创建NSArray

 NSArray *studentkeys = [NSArray arrayWithObjects:@"studentName", @"studentBirthDate", @"studentCity", @"studentMobile" nil]; NSArray *objects = [NSArray arrayWithObjects:@"Pravin", @"27/08/1990", @"Bhavnagar",@"7878007531", nil]; 

…使用NSDictionary访问NSArray对象

 NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

这是结构:
您的根对象是NSMutableDictionary
eventData – 具有键和对象的对象NSMutableDictionary的键:
– > key eventDate对象NSString
– > key eventLocation对象带有键和对象的NSMutableDictionary
—->键latitude对象NSNumber
—->关键longitude对象NSNumber
– >关键text对象NSString
– > key imageData对象NSString后来转换为NSData
– >关键imageFormat对象NSString
– > key expirationTime对象NSNumber
对象NSString type
对象NSString title

如果您想要多个类别,可以使用此格式

 NSDictionary *jsonObject = @{ @"data1":@[ @{ @"title":@"A" @"subData" : @[ @{ @"title":@"aa" }] } ] };