创建NSDictionary

时间:2016-06-03 12:43:13

标签: ios objective-c json nsdictionary

我怎么能创建Dictionary,当我用它创建jsondata时,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";
};

3 个答案:

答案 0 :(得分:1)

您错过了一个级别:NSDictionary(顶级),顶级关键NSArray中的{strong> 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];

答案 1 :(得分:0)

您的代码应该是,

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

你错过了

之间的一个数组

答案 2 :(得分:0)

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

使用此代码,它将完美运作。