NSDictionary格式

时间:2015-08-06 10:21:27

标签: ios objective-c json nsarray nsdictionary

有人可以帮我创建以下结构的NSDictionary格式:

{
key1 = "value1";
    key2 = "value2";
    key3 =     [
                {
            key01 = "value01";
            key02 = "value02";
        },
                {
            key01 = "value01";
            key02 = "value02";
        },
                {
            key01 = "value01";
            key02 = "value02";
        }
    ];
}

4 个答案:

答案 0 :(得分:3)

尝试使用此代码可能会对您有所帮助。

NSDictionary *dicationary = @{
                                  @"key1":@"value1",
                                  @"key2":@"value2",
                                  @"key3":@[@{@"key01":@"value01",@"key02":@"value02"},
                                            @{@"key01":@"value01",@"key02":@"value02"},
                                            @{@"key01":@"value01",@"key02":@"value02"}]
                                  };

答案 1 :(得分:1)

obj-c中有API将Json转换为nsdictionary。我猜你应该试试:

  1. 首先将json转换为nsdata(假设您上面的JSON是字符串格式)
  2. 2.然后你将API转换为NSDictionary:

    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    

答案 2 :(得分:0)

以下内容对您有用:

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSLog(@"%@", jsonDict[@"ID"][@"Content"]);

会回复你: 268

答案 3 :(得分:0)

只是回答关于将JSON数据转换为NSDictionary的问题,这里是:

(假设您已经获得了JSON数据)

// add the first 2 VALUES with it's KEYS
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:VALUE1 forKey:KEY1];
[mainDict setValue:VALUE2 forKey:KEY2];

// then for the last KEY, create a mutable array where you will store your sub dictionaries
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY1];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY2];
[ma addObject:subDict];

// then add that array to your main dictionary
[mainDict setValue:ma forKey:KEY3];

// check the output
NSLog(@"mainDict : %@", mainDict);
// SAMPLE DATA - Test this if this is what you want
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:@"value1" forKey:@"key1"];
[mainDict setValue:@"value2" forKey:@"key2"];

NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:@"subValue1" forKey:@"subKey1"];
[subDict setValue:@"subValue2" forKey:@"subKey2"];
[ma addObject:subDict];

[mainDict setValue:ma forKey:@"key3"];

NSLog(@"mainDict : %@", mainDict);