Noob在这里。我最近开始使用目标C,目前我坚持使用字典概念。我想创建一个json对象,如下所示:
{"UserData": {
"Name": Mike Smith,
"Age": 32,
"category": [1,2,3],
"Weekly Data": [
{"Monday" : [1.0,2.0,3.0]},
{"Tuesday": [1.0,2.0,3.0]}
]
}
}
我编写了以下代码,但未提供所需的结果。我想知道是否有人可以帮助我。
-(NSString*)populateUserPreferences
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *categorydata = [[NSMutableArray alloc] init];
NSMutableArray *weeklydata = [[NSMutableArray alloc] init];
for (int i=0;i<4; i++)
{
[categorydata addObject:[NSNumber numberWithInt:i]];
}
NSMutableArray *mondaydata = [[NSMutableArray alloc] init];
for (int j=0; j<3; j++)
{
[mondaydata addObject:[NSNumber numberWithInt:j]];
}
NSMutableArray *tuesdaydata = [[NSMutableArray alloc] init];
for (int j=0; j<3; j++)
{
[tuesdaydata addObject:[NSNumber numberWithInt:j]];
}
NSDictionary *monday = [NSDictionary dictionaryWithObject:mondaydata];
NSDictionary *tuesday = [NSDictionary dictionaryWithObject:tuesdaydata];
[weeklydata addObject: monday ];
[weeklydata addObject: tuesday ];
}
[dict setObject:[NSString stringWithFormat:"Mike Smith"] forKey:@"Name"];
[dict setObject:[NSNumber numberWithInteger:32.0] forKey:@"Age"];
[dict setObject:categorydata forKey:@"category"];
[dict setObject:weeklydata forKey:@"Weekly Data"];
NSString * userdata = [dict JSONRepresentation];
NSLog(request);
NSDictionary *userdataJson = [NSDictionary dictionaryWithObject:dict forKey:@"userData"];
return [userdataJson JSONRepresentation];
}
提前感谢您对此进行调查。
Apoorva
答案 0 :(得分:0)
错误在于创建星期一和星期二字典。
const http = require('http');
const server = http.createServer((req,res) => {
const data = {
'data': 'Hello World',
'hostname': require('os').hostname()
};
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(JSON.stringify(data));
});
server.listen(process.env.PORT, (err) => {
if (err)
return console.log(err);
console.log('API is running on ' + process.env.PORT);
})
此代码错误,因为您没有正确分配字典(字典的键在哪里?)。相反,你应该这样做:
// mondaydata & tuesday is just array.
NSDictionary *monday = [NSDictionary dictionaryWithObject:mondaydata];
NSDictionary *tuesday = [NSDictionary dictionaryWithObject:tuesdaydata];
然后你可以将mondayDict和tuesdayDict添加到你的数组weeklydata。
PS。只是一个注释,有意义地命名您的变量。例如,mondaydata不够描述。你应该使用mondayArr作为例子。要轻松识别它是一个数组。只是一个正常的编码实践来分享。
答案 1 :(得分:0)
NSDictionary * dict = @{@"UserData": @{
@"Name": @"Mike Smith",
@"Age": @32,
@"category": @[@1,@2,@3],
@"Weekly Data": @[
@{@"Monday" : @[@1.0,@2.0,@3.0]},
@{@"Tuesday": @[@1.0,@2.0,@3.0]}
]
}
};
NSError * error = nil;
NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(@"%@", [error localizedDescription]);
} else {
// Do what you want
}