Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

iphone - creating JSON format in Objective C

For an application i want to create a JSON in format as mentioned below,

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

I am using the following code to create the same,

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

I am getting in the following format,

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

} }

could someone please help me in creating the format.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Required Data , You can get this way . Just convert that stud dict in JSon or any other format you want. Remove that array , You don't need it , As you mentioned it in the required format.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...