创建 NSDictionary

Creating NSDictionary

我如何创建字典,当我用它创建 json数据时,json 看起来像:

 "historyStep":[

{
"counter": "50",
"timestamp": "1461674383632"
}
 ]

我这样做了:

NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:@(810) forKey:@"counter"];
[jsonDictOth setObject:@"1464957395241.447998" forKey:@"timestamp"];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:jsonDictOth,@"historyStep", nil];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

但它看起来:

 historyStep =     {
    counter = 810;
    timestamp = "1464957395241.447998";
};

你的代码应该是这样的,

   NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:@(810) forKey:@"counter"];
[jsonDictOth setObject:@"1464957395241.447998" forKey:@"timestamp"];

NSMutableArray *arr = [[NSMutableArray alloc]init];

[arr addObject:jsonDictOth];

NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr,@"historyStep", nil];
NSLog(@"jsonMain is %@",jsonDictMain);
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
                                               options:0
                                                 error:&error];

它的输出是,

jsonMain is {
historyStep =     (
            {
        counter = 810;
        timestamp = "1464957395241.447998";
    }
 );
}

您刚刚错过了一个数组

NSDictionary *innerDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:@"50", @"counter",@"1461674383632", @"timestamp", nil];
NSArray *array = [[NSArray alloc]initWithObjects:innerDictionary, nil];
NSDictionary *outerDict = [[NSDictionary alloc]initWithObjectsAndKeys:array, @"historyStep", nil];

使用此代码将完美运行。

您缺少一个级别:NSDictionary(顶级),其中 NSArray of NSDictionary 在顶级键 historyStep:

NSMutableDictionary *topLevel = [[NSMutableDictionary alloc] init];


NSArray *historySteps = [[NSMutableArray alloc] init];
//Here you may have a for loop in case there are more steps
NSDictionary *aStep = @{@"counter":@"50", @"timestamp":@"1461674383632"};
[historySteps addObject:aStep]

[topLevel setObject:historySteps forKey@"historyStep"];

NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:topLevel
                                               options:NSJSONWritingPrettyPrinted
                                                 error:&error];