小编典典

在目标C中创建JSON格式

json

对于一个应用程序,我想按如下所述创建JSON格式,

"Students" : {
    "results": {
        "Grade1": {
            "studentresult": "pass",
            "marksheet": "provided"
        },
        "ID": 01,
        "Name": "Student1", 
    }
}

我正在使用以下代码创建相同的代码,

NSMutableDictionary *gradedetails = [[NSMutableDictionary alloc] init];
[gradedetails setObject:@"pass" forKey:@"studentresult"];
[gradedetails setObject:@"provided" forKey:@"marksheet"];

NSMutableDictionary *sdetails = [[NSMutableDictionary alloc] init];
[sdetails setObject:@"01" forKey:@"ID"];
[sdetails setObject:@"Name" forKey:@"Student1"];

NSMutableDictionary *grade = [[NSMutableDictionary alloc] init];
[grade setObject:gradedetails forKey:@"Grade1"];

NSMutableArray *rarray = [[NSMutableArray alloc] init];
[rarray addObject:grade];
[rarray addObject:sdetails];

NSMutableDictionary *results = [[NSMutableDictionary alloc] init];
[results setObject:rarray forKey:@"results"];

NSMutableDictionary *stud = [[NSMutableDictionary alloc] init];
[stud setObject:rdic forKey:@"Students"];

NSData *jsondata = [NSJSONSerialization dataWithJSONObject:stud options:NSJSONWritingPrettyPrinted error:&error];

我的格式如下,

"Students" : {
"results" : [
  {
    "Grade1" : {
      "studentresult" : "pass",
      "marksheet" : "provided" 
    }
  },
  {
    "ID" : "01",
    "Name" : "Student1"
  }
]

}}

有人可以帮我创建格式吗?

谢谢。


阅读 251

收藏
2020-07-27

共1个答案

小编典典

所需数据,您可以通过这种方式获得。只需将其dict转换为JSon或您想要的任何其他格式即可。删除该数组,您不需要它,正如您以要求的格式提到的那样。

NSMutableDictionary *gradedetails = [[NSMutableDictionary alloc] init];
[gradedetails setObject:@"pass" forKey:@"studentresult"];
[gradedetails setObject:@"provided" forKey:@"marksheet"];

NSMutableDictionary *sdetails = [[NSMutableDictionary alloc] init];
[sdetails setObject:@"01" forKey:@"ID"];
[sdetails setObject:@"Name" forKey:@"Student1"];
[sdetails setObject:gradedetails forKey:@"Grade1"];

NSMutableDictionary *results = [[NSMutableDictionary alloc] init];
[results setObject:sdetails forKey:@"results"];

NSMutableDictionary *stud = [[NSMutableDictionary alloc] init];
[stud setObject:results forKey:@"Students"];

NSLog(@"Required Format Data is %@",stud);
2020-07-27