所以我有两个对象:
对象1:
{
"Details": {
"name": "John"
"age": 34
}
}
对象2:
{
"MoreInfo": {
"Title": "Mr"
}
}
我想从这两个对象中创建一个JSON对象,看起来像这样:
{
"Details1": {
"Details": {
"name": "John"
"age": 34
}
},
"Details2": {
"MoreInfo": {
"Title": "Mr"
}
}
}
我尝试了各种不同的方法(转换为字典并合并,附加多余的字符串{),但我似乎无法解决这个问题。 有人有什么想法吗?
答案 0 :(得分:0)
我不确定,但是我认为这行代码可能对您有帮助
NSDictionary *userInfo = @{ @"name": @"John",@"age": @34 };
NSDictionary *userMoreInfo = @{ @"Title": @"Mr", };
NSDictionary *Details = [NSDictionary dictionaryWithObject:userInfo forKey:@"Details"];
NSDictionary *MoreInfo = [NSDictionary dictionaryWithObject:userMoreInfo forKey:@"MoreInfo"];
NSMutableDictionary *finalDictThatWants = [NSMutableDictionary new];
[finalDictThatWants setObject:Details forKey:@"Details1"];
[finalDictThatWants setObject:MoreInfo forKey:@"Details2"];
答案 1 :(得分:0)
不确定为什么要使用可变字典...
NSDictionary *details1 = @{
@"Details": @{
@"name": @"John",
@"age": @34
}
};
NSDictionary *details2 = @{
@"MoreInfo": @{
@"Title": @"Mr"
}
};
NSData *data = [NSJSONSerialization dataWithJSONObject:@{
@"Details1": details1,
@"Details2": details2
}
options:NSJSONWritingPrettyPrinted
error:nil];
NSLog(@"\n%@", [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
输出
{
"Details2" : {
"MoreInfo" : {
"Title" : "Mr"
}
},
"Details1" : {
"Details" : {
"name" : "John",
"age" : 34
}
}
}