How to parse JSON data in iOS objective-c [duplicate] - ios
This question already has answers here:
How to parse JSON in Objective-C
(2 answers)
Closed 6 years ago.
I have JSON DATA
{"respcode":0,"policyid":"1731958","Insuredid":"5625869"}
How can I get respcode, policyid and Insuredid in individual variable using parsing.
Try out the below code:
NSString* path = [[NSBundle mainBundle] pathForResource:#"JSON" ofType:#"json"];
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSString *insuredId = [responseDictionary objectForKey:#"Insuredid"];
NSString *policyid = [responseDictionary objectForKey:#"policyid"];
NSString *respcode = [responseDictionary objectForKey:#"respcode"];
NSLog(#"insuredId : %# & policyid : %# & respcode : %#",insuredId,policyid,respcode);
} else {
NSLog(#"Error in parsing JSON");
}
//JSON.json
{"respcode":0,"policyid":"1731958","Insuredid":"5625869"}
Edited If your JSON DATA is already a Dictionary, you can access them using:
NSLog(#"%#",jsonData[#"respcode"]); // 0
NSLog(#"%#",jsonData[#"policyid"]); // 1731958
NSLog(#"%#",jsonData[#"Insuredid"]); // 5625869
I hope this can help you. If not, let me know more information about your code, so I can try a better answer.
Related
get values out of jSON Array - Objective C [duplicate]
This question already has answers here: Get values from NSDictionary (3 answers) Closed 6 years ago. I am new to objective-c and iOS development. I need to get json values from a url and get values out of it. This is the json value I am getting. "\"[{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":\\\"06c6b36f-0d05-4f0c-bdee-1744c2cb6519\\\",\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"baman123 has joined the chat!\\\",\\\"IsJoin\\\":true,\\\"MessageTime\\\":\\\"2017-01-09 06:25:47\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"JoinMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"hi this is baman\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:01:07\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"are you there\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:01:10\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"fuck u\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:01:14\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"sathyabaman\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:37:15\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null}]\"" And I tried to get values out + (void) showCurrentHistory:(NSString *) historyString { NSLog(#"Received String : %#", historyString); NSData *data = [historyString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e]; for (NSDictionary *dic in jsonArray) { NSString *VisitorId = [dic objectForKey:#"VisitorId"]; NSString *VisitorSignalId = [dic objectForKey:#"VisitorSignalId"]; NSString *Type = [dic objectForKey:#"Type"]; NSString *Messagetext = [dic objectForKey:#"Messagetext"]; NSString *MessageTime = [dic objectForKey:#"MessageTime"]; NSString *Image = [dic objectForKey:#"Image"]; NSString *FileUploadDetails = [dic objectForKey:#"FileUploadDetails"]; NSString *FirstOperatorName = [dic objectForKey:#"FirstOperatorName"]; NSString *Rating = [dic objectForKey:#"Rating"]; NSLog(#"----------------------- Current Chat History --------------------------------"); NSLog(#"VisitorId : %#" , VisitorId); NSLog(#"VisitorSignalId : %#", VisitorSignalId); NSLog(#"Type : %#" , Type); NSLog(#"Messagetext : %#" , Messagetext); NSLog(#"MessageTime : %#" , MessageTime); NSLog(#"Image : %#", Image); NSLog(#"FileUploadDetails : %#" , FileUploadDetails); NSLog(#"FirstOperatorName : %#" , FirstOperatorName); NSLog(#"Rating : %#" , Rating); NSLog(#"------------------------------------------------------------------------------"); } } But its not entering the for loop. Can someone help me to fix this tnx.
Your JSON String may contains extra \\ so you have to remove that one. Please check below JSON string and code. NSString *str = #"[{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":\"06c6b36f-0d05-4f0c-bdee-1744c2cb6519\",\"Type\":\"Visitor\",\"Messagetext\":\"baman123 has joined the chat!\",\"IsJoin\":true,\"MessageTime\":\"2017-01-09 06:25:47\",\"File\":null,\"MessageType\":\"JoinMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"hi this is baman\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:01:07\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"are you there\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:01:10\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"fuck u\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:01:14\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"sathyabaman\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:37:15\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null}]"; NSData *data = [[NSData alloc] initWithBytes:[str UTF8String] length:str.length]; NSError *error; NSMutableArray response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; Hope this will helps to solve your problem.
You are getting json string, you can convert json object from it like, id jsonString = yourJsonStringHere; NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(#"%#",jsonObject);
NSJSONSerialization Returns Error of NULL
I have the following code : NSData * jsonData = [NSData dataWithContentsOfURL:location]; NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSData *data = [newStr dataUsingEncoding:NSUTF8StringEncoding]; NSError *jsonError; if (jsonError) { NSLog(#"JSON Error %#", [jsonError localizedDescription]); } NSArray * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; Which is parsing the following JSON String : {"author":"Oli Riman","content":"The museum shows us a view of pre-WWI society that includes doubts, fears, political protests etc. through newspaper cartoons of the time. Really interesting for adults who enjoy history. I wouldn't suggest this for kids who haven't studied WWI history or who don't read easily.","rating":"5","placeId":"40","date":"29-June-2015","reviewId":"9905A52D-76B2-4D42-8CA8-9158225C0D07"} However I am getting a strange error code of : domain: (null) - code: 0 Can anyone advise on what is causing this ?
Just tested the code on my simulator. Its working. You need to check if you are getting data from server or not. If you want to test the parsing thing, you can do one thing- Just store the data in json file and save it in the app bundle lets say file is "data.json" and call below method, you will get data for sure. - (void)readJsonData { NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"]; NSURL *url = [NSURL fileURLWithPath:path]; NSData *data = [NSData dataWithContentsOfURL:url]; NSError *error; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: &error]; NSLog(#"Parsed json data- %#", dict); }
iOS - How to properly read JSON file with umlauts
I am having difficulties converting a JSON file into an NSDictionary without losing umlauts. { "België": "5", "Haïti": "45" } This is a short version of the contents of a .json file in my supporting files in Xcode. I need to convert them to an NSDictionary without losing those umlauts. NSString *file =[[NSBundle mainBundle] pathForResource:#"countries_and_rates" ofType:#"json"]; NSString *cr = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:NULL]; After that, I give cr to this method: + (NSDictionary*)jsonFromData:(NSData*)data { if([self isEmpty:data] || ![data isKindOfClass:[NSData class]]) return nil; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if(!str) return nil; NSError* error; id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; if(error) NSLog(#"************** Error: jsonFromData: %#/%#", error.localizedDescription, error); if([json isKindOfClass:[NSDictionary class]]) return json; else if([json isKindOfClass:[NSArray class]]) return [NSDictionary dictionaryWithObject:json forKey:#"results"]; return #{}; } If someone could help me and tell me what I am doing wrong. FYI: tried all kinds of encoding, such as NSISO and NSUTF
Don't mess around with encodings, let the framework figure it out for you: NSData *data = [NSData dataWithContentsOfFile:filepath]; NSError *error = nil; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Json to iOS Encoding Error
Problem: I can't parse data from a JSON file to a NSArray appropriately. UTF encoding is not working as expected. My JSON looks something like: [ {"Name":"Marcos","Address":"1234 Brasil Av. São Paulo - SP","Latitude":"-23.000","Longitude":"-46.70"},{"Name":"Mario","Address":"1000 Washignton Luiz Av. Itú SP","Latitude":"-20.0000","Longitude":"-46.000"} ] My Objective-C code is: NSError *error = nil; NSURL *jsonUrl = [[NSURL alloc]initWithString: #"http://marcosdegni.com.br/teste/webservice_teste.php"]; NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl encoding:NSUTF8StringEncoding error:&error]; NSLog(#"jsonString: %# , Error:%#:" ,jsonString, error); //(1) if (!error) { NSError *error2 = nil; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSArray * jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error2]; NSLog(#"\n\nArray: %#" \nError:$#, jsonArray, error2); //(2) //(*1*) This log show the content's as they are expected: note the characters ã and ú on the address fields. //(*2*) The logs from the array and the dictionary show this charters as it's UNIX codes:\U00e and \U00fa respectively.
You can give this a try. The id json you get will be a NSArray, you can use it from there. NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSArray * array = json; for (NSDictionary *dict in array) { NSString *string = [dict objectForKey:#"Address"]; NSLog(#"%#",string); } From here, and I get the right result if I obtain the value of the key and log it, instead of logging the NSArray directly.
How to get the values from json service [duplicate]
This question already has an answer here: Parsing JSON response . (1 answer) Closed 8 years ago. Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance.. NSString *Username= txtUsername.text; NSString *Password=txtPassword.text; NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password]; NSURL *url=[NSURL URLWithString:link]; NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the key . Before getting any value , we have to understand the tree of jSon. Here "posts" is an NSArray ,within that one DIctionary "post" is there ,which again contains another dictionary. Below is the complete code. (void)viewDidLoad { [super viewDidLoad]; NSString *Username= txtUsername.text; NSString *Password=txtPassword.text; NSString *link = [NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password]; dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL]; [self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES]; }); } Then call that selector fetchedData (void)fetchedData:(NSData *)responseData { //parse out the json data NSError* error; NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; if(!error){ NSArray* postArray = [json objectForKey:#“posts”]; //This is an array if (postArray.count>0) { NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ]; NSString *id_ = [dict objectForKey:#"id"]; NSString *status_ = [dict objectForKey:#"status"]; } } }
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS NSString *Username= txtUsername.text; NSString *Password=txtPassword.text; NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password]; NSURL *url=[NSURL URLWithString:link]; NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url]; NSURLResponse *response; NSError *error; //getting the data NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error]; NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding]; NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString); NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding]; NSError *myError = nil; NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError]; NSString *id=[res objectForKey:#"ID"]; NSString *status=[res objectForKey:#"Status"]; and if u need extra info please go through below link it may help you Click here for more details