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.
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);
Depends on your code:
NSMutableDictionary *gradedetails = [[NSMutableDictionary alloc] init];
[gradedetails setObject:#"pass" forKey:#"studentresult"];
[gradedetails setObject:#"provided" forKey:#"marksheet"];
NSMutableDictionary *results = [[NSMutableDictionary alloc] init];
[results setObject:gradedetails forKey:#"Grade1"];
[results setObject:#"01" forKey:#"ID"];
[results setObject:#"Name" forKey:#"Student1"];
NSMutableDictionary *stud = [[NSMutableDictionary alloc] init];
[stud setObject:results forKey:#"Students"];
NSDictionary *gradedetails = #{#"studentresult" : #"pass", #"marksheet" : #"provided"};
NSDictionary *grade = #{ #"Grade1" : gradedetails}
NSDictionary *sdetails = #{#"ID" : #"01", #"Student1" : #"Name"};
NSArray *resultsArray = #[grade, sdetails];
NSDictionary *results= #{#"results" : resultsArray};
NSDictionary *stud = #{#"Students" : results};
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:stud options:NSJSONWritingPrettyPrinted error:&error];
I wonder why few developper use this notation
check this code-
NSMutableDictionary *students=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
for (NSDictionary *dictionofstudents in students)
{
NSMutableDictionary *results=[dictionofstudents objectForKey:#"results"];
for (NSDictionary *dictionofresults in results)
{
NSMutableDictionary *grade1=[dictionofresults objectForKey:#"Grade1"];
for (NSDictionary *dictionofgrade1 in grade1)
{
NSString *studentresult=[dictionofgrade1 objectForKey:#"studentresult"];
NSString *marksheet=[dictionofgrade1 objectForKey:#"marksheet"];
[arrayofstudentresult addObject:studentresult];
[arrayofmarksheet addObject:marksheet];
}
NSString *ID=[dictionofresults objectForKey:#"ID"];
NSString *name=[dictionofresults objectForKey:#"Name"];
[arrayofID addObject:ID];
[arrayofname addObject:name];
}
}
In order to get the format you want out of it, you have to pack information in that particular format.
Your problem is right about here:
NSMutableArray *rarray = [[NSMutableArray alloc] init];
[rarray addObject:grade];
[rarray addObject:sdetails];
The desired format has no arrays, so why are you creating an array?
A hint for you:
You should be creating exactly 4 dictionaries, and no arrays.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
NSMutableDictionary *grade = [[NSMutableDictionary alloc] init];
[grade setValue:#"pass" forKey:#"studentresult"];
[grade setValue:#"provided" forKey:#"marksheet"];
[result setValue:grade forKey:#"Grade1"];
[result setValue:#"01" forKey:#"ID"];
[result setValue:#"Student1" forKey:#"Name"];
[dict setValue:result forKey:#"results"];
NSMutableDictionary *stdnt = [[NSMutableDictionary alloc] init];
[stdnt setValue:dict forKey:#"Students"];
NSError *error = nil;
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:stdnt options:NSJSONWritingPrettyPrinted error:&error];
NSString *s = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
NSLog(#"%#",s);
It may helps you.
Related
Here is my dictionary result.
"continent_code" = EU;
"country_code" = gb;
"country_id" = 169;
"country_name" = "United Kingdom";
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSDictionary *LoginResult = (NSDictionary*)[responseString JSONValue];
I want to retrieve only country name to NSArray from dictionary.
Try This ::
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&error];
NSLog(#" Value :: %#", [[jsonArray JSONRepresentation] JSONValue]);
for (NSDictionary *item in jsonArray) {
NSLog(#" Item :::::> %#", [item objectForKey:#"country_name"]);
}
Hope, It'll help you.
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:#"RootName"];
NSMutableArray *loginArray = [[NSMutableArray alloc]init];
for(int i = 0 ; i<[loginArray count];i++)
{
NSString *countryName=[[loginArray objectAtIndex:i]objectForKey:#"country_name"];
[loginArray addObject:countryName];
}
Good luck !!
The Correct Method to fill countryArray :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:yourResponseData options:kNilOptions error:&error];
NSArray* getMAS_CR = [(NSDictionary*)json objectForKey:#"yourKeyRootResult"];
NSMutableArray *countryArray = [[NSMutableArray alloc]init];
for (NSDictionary *rr in getMAS_CR)
{
NSString *cName = [NSString stringWithFormat:#"%#",[rr objectForKey:#"country_name"]];
[countryArray addObject:cName];
}
NSLog(#"countryArray :: %#",countryArray);
GoodLuck.
-(void) httpDataDidFinishLoadingWithData:(NSData *)theData
{
m_activityLoaded=NO;
temp=[[NSString alloc] initWithData:[dataLoader httpData]
encoding:NSUTF8StringEncoding];
NSLog(#"TEMP IS TEMP %#", temp);
NSDictionary *dict = [[NSDictionary alloc]init];
dict = [[temp JSONValue] objectForKey:#"location"];
NSDictionary *dict1 = [[NSDictionary alloc]init];
dict1 = [[temp JSONValue] objectForKey:#"wind"];
NSDictionary *dict2 = [[NSDictionary alloc]init];
dict2 = [dict1 objectForKey:#"direction"];
NSDictionary *dict3 = [[NSDictionary alloc]init];
dict3 = [[temp JSONValue] objectForKey:#"atmosphere"];
NSDictionary *dict4 = [[NSDictionary alloc]init];
dict4 = [[temp JSONValue] objectForKey:#"condition"];
NSDictionary *dict5 = [[NSDictionary alloc]init];
dict5 = [dict4 objectForKey:#"text"];
NSDictionary *dict6 = [[NSDictionary alloc]init];
dict6 = [dict4 objectForKey:#"code"];
NSDictionary *dict7 = [[NSDictionary alloc]init];
dict7 = [dict4 objectForKey:#"temperature"];
temperatureLabel.text = [dict4 objectForKey:#"temperature"];
}
Crash occurs at temperatureLabel.text = [dict4 objectForKey:#"temperature"];
I dont know man, Data is exactly printed in the console, but crashing at UILABEL(temperatureLabel). Help me out, thanks in advance
if you look at the error you are getting it is telling you that the object return for the key temperature is not a NSString or NSDictionary but a NSNumber.
Give this a try:
-(void) httpDataDidFinishLoadingWithData:(NSData *)theData {
m_activityLoaded=NO;
temp=[[NSString alloc] initWithData:[dataLoader httpData]
encoding:NSUTF8StringEncoding];
NSLog(#"TEMP IS TEMP %#", temp);
NSDictionary *dict = [[temp JSONValue] objectForKey:#"location"];
NSDictionary *dict1 = [[temp JSONValue] objectForKey:#"wind"];
NSDictionary *dict2 = [dict1 objectForKey:#"direction"];
NSDictionary *dict3 = [[temp JSONValue] objectForKey:#"atmosphere"];
NSDictionary *dict4 = [[temp JSONValue] objectForKey:#"condition"];
NSDictionary *dict5 = [dict4 objectForKey:#"text"];
NSDictionary *dict6 = [dict4 objectForKey:#"code"];
NSNumber *temperature = [dict4 objectForKey:#"temperature"];
temperatureLabel.text = [NSString stringWithFormat:#"%#", temperature];
}
You might want to look at NSNumberFormatter for formatter the temperature with something like: °F or °C.
Are you sure that your object is of NSString class?
Try putting in something like:
if([[dict4 objectForKey:#"temperature"] isKindOfClass:[NSString class]])
NSLog(#"lalala");
If it does not get logged to the console it means that your object is not an NSString and you could try something like:
temperatureLabel.text = [NSString stringWithFormat:#"%#", [dict4 objectForKey:#"temperature"]];
You should change the %# according to the kind of object you have stored in your dictionnary.
Your dictionary contains an NSNumber instance and you are assigning that to a property of type NSString. The crash message is your tip off there. Use stringValue or some other way to get the number's data into string form.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in Objective-C with SBJSON
I have below JSON Response (String). I want to parse it into an NSArray with all the patient names.
[{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"},
{"pat_reg_no":"111181031P2","app_start_time":"11.15","pat_firstname":"Shane Watson"},
{"pat_reg_no":"111181031P3","app_start_time":"12.15","pat_firstname":"Michael Hussey"},
{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}]
How do I parse this?
I write a demo for you.
SBJsonParser *parser = [[SBJsonParser alloc] init];
id jsonObj = [parser objectWithString:#"[{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"},{\"pat_reg_no\":\"111181031P2\",\"app_start_time\":\"11.15\",\"pat_firstname\":\"Shane Watson\"},{\"pat_reg_no\":\"111181031P3\",\"app_start_time\":\"12.15\",\"pat_firstname\":\"Michael Hussey\"},{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"}]"];
if ([jsonObj isKindOfClass:[NSArray class]]) {
for (id obj in jsonObj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSString *name = [obj objectForKey:#"pat_firstname"];
NSLog(#"name %#", name);
}
}
}
[parser release];
Try Below Code.
NSString* jsonString;
//jsonString suppose this String has That JSON Response.
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSArray *pat_reg_noArray = [jsonResponse valueForKey:#"pat_reg_no"] ;
NSArray *app_start_timeArray= [jsonResponse valueForKey:#"app_start_time"] ;
NSArray*firstnameArray=[jsonResponse valueForKey:#"pat_firstname"];
I hope It 'll work.
The Array which you have posted belongs to someKey, so do the following
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:YourString];
NSArray * array = [dictionary objectForKey:someKey];
NSMutableArray *nameArray = [NSMutableArray new];
for (NSDictionary *dict in array)
{
[nameArray addObject:[dict objectForKey:#"pat_firstname"];
}
NSLog(#"x is %#",nameArray);
[jsonParser release];
Hope this will solve your problem...
Try this:
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray* array = [(NSDictionary*)[jsonString JSONValue] objectForKey:#"results"];
simple question, I need to structure data in the following format:
UserID:
1 {
Name = Bob
Surname = Hope
}
2 {
...
I can used an NSMutableDictionary to add a single layer with keys, but I am unable to create a child associate with a certain key.
I have tried creating a mutable dictionary and assigning that to a key:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *keys = [[NSArray alloc] initWithObjects:#"Name", #"Surname", nil];
NSArray *details = [[NSArray alloc] initWithObjects:#"Bob",#"Hope", nil];
NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];
[dic setValue:#"1" forKey:#"id"];
[[dic objectForKey:#"id"] setDictionary: person];
I think it is better to use an array of dictionaries, each dictionary representing a user.
NSMutableArray *users= [[NSMutableArray alloc] init];
NSArray *keys = [[NSArray alloc] initWithObjects:#"Name", #"Surname", nil];
NSArray *details = [[NSArray alloc] initWithObjects:#"Bob",#"Hope", nil];
NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];
[users addObject:person];
u can also set the objects for dictionary in this way
[dic setObject:person forKey:#"id"];
I am parsing the data it gets all the data in dictionary but when i check value using NSLog it showa nil value
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0];
appDelegate.books1 = [[NSMutableArray alloc] init];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book1 *aBook = [[Book1 alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books1 addObject:aBook];
Book1 *mybook=[appDelegate.books1 objectAtIndex:i];
NSString*test=mybook.location;
NSLog(test);
}
Dicionary parsing
- (id)initWithDictionary:(NSDictionary*) dict {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
return self;
}
I'm guessing that your dictionary doesn't contain a "location", and that's consistent with what I see coming back from that web site. It sends back an array of dictionaries which contain arrays of dictionaries. You need to extract one of those inner dictionaries to find a "location".
[
{
"date":1320883200000,
"events":[
{
"affectedDate":1320883200000,
"event":{
"appId":620,
"eventId":20672,
"location":"Samsen Kulturhus",
"municipality":"Kristiansand",
"title":"AKKS kurs høsten 2011"
}
},
....
Try:
- (id)initWithDictionary:(NSDictionary*) dict {
self = [super init];
if(self) {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
}
return self;
}