NS字典格式

NSDictionary format

谁能帮我创建一个具有以下结构的 NSDictionary 格式:

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

试试这个代码,它可能对你有帮助。

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

以下应该适合您:

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

你会return: 268

obj-c 中有 API 可以将 Json 转换为 nsdictionary。我想你应该试试看:

  1. 先把json转成nsdata(假设你上面的JSON是字符串格式)

2.Then 你 API 将其转换为 NSDictionary :

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

只是为了回答您关于将 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);