Parse JSON response string in Objective - C [duplicate] - ios

This question already has answers here:
How to convert a Json String into a NSArray? [closed]
(2 answers)
How do I parse JSON with Objective-C?
(5 answers)
Closed 6 years ago.
"[
{
\"TheatreName\": \"FunCinemas\",
\"TheatreId\": 1,
\"City\": \"Chandigarh\"
},
{
\"TheatreName\": \"PVRElanteMall\",
\"TheatreId\": 2,
\"City\": \"Chandigarh\"
},
{
\"TheatreName\": \"PiccadilySquare\",
\"TheatreId\": 3,
\"City\": \"Chandigarh\"
}
]"
I want to parse these data, that is separate all the objects Theatrename, id, city

I tried to create a demo scenario with your JSON value
Here is the code :
- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = #"[{\"TheatreName\": \"FunCinemas\",\"TheatreId\": 1,\"City\":\"Chandigarh\"},{\"TheatreName\":\"PVRElanteMall\",\"TheatreId\": 2,\"City\": \"Chandigarh\"},{\"TheatreName\": \"PiccadilySquare\",\"TheatreId\": 3,\"City\": \"Chandigarh\"}]";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *err = nil;
NSArray *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
NSMutableArray *arrResult = [NSMutableArray array];
for (NSDictionary *dict in jsonData) {
NSLog(#"TheatreName %#", dict[#"TheatreName"]);
NSLog(#"TheatreId %#", dict[#"TheatreId"]);
NSLog(#"City %#", dict[#"City"]);
[arrResult addObject:dict];
}
}

Related

Get values from NSDictionary

Hi I'm new to iOS development. I want to get response and add those values to variable.
I tried it but I'm getting below response. I don't understand why there is slashes in this response.
#"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]"
I tried this :
- (void) sendOtherActiveChats:(NSDictionary *) chatDetails{
NSLog(#"inside sendOtherActiveChats");
NSLog(#"otherDetails Dictionary : %# ", chatDetails);
NSString *VisitorID = [chatDetails objectForKey:#"VisitorID"];
NSString *ProfileID = [chatDetails objectForKey:#"ProfileID"];
NSString *CompanyID = [chatDetails objectForKey:#"CompanyID"];
NSString *VisitorName = [chatDetails objectForKey:#"VisitorName"];
NSString *OperatorName = [chatDetails objectForKey:#"OperatorName"];
NSString *isocode = [chatDetails objectForKey:#"isocode"];
NSLog(#"------------------------Other Active Chats -----------------------------------");
NSLog(#"VisitorID : %#" , VisitorID);
NSLog(#"ProfileID : %#" , ProfileID);
NSLog(#"CompanyID : %#" , CompanyID);
NSLog(#"VisitorName : %#" , VisitorName);
NSLog(#"OperatorName : %#" , OperatorName);
NSLog(#"countryCode: %#" , isocode);
NSLog(#"------------------------------------------------------------------------------");
}
Can some one help me to get the values out of this string ?
You are getting Array of Dictionary in response, but your response is in string so you convert it to NSArray using NSJSONSerialization like this way for that convert your response string to NSData and after that use that data with JSONObjectWithData: to get array from it.
NSString *jsonString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
Now loop through the array and access the each dictionary from it.
for (NSDictionary *dic in jsonArray) {
NSLog(#"%#",[dic objectForKey:#"VisitorID"]);
... and so on.
}
First you need to parse your string.
NSString *aString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [aString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[[json objectAtIndex:0] objectForKey:#"VisitorID"]);
So you have JSON string and array of 2 objects. So write following code
This will convert JSON string to Array
NSData *myJSONData = [YOUR_JSON_STRING dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableArray *arrayResponse = [NSJSONSerialization JSONObjectWithData:myJSONData options:NSJSONReadingMutableContainers error:&error];
Now use for loop and print data as
for (int i = 0; i < arrayResponse.count; i++) {
NSDictionary *dictionaryTemp = [arrayResponse objectAtIndex:i];
NSLog(#"VisitorID : %#",[dictionaryTemp valueForKey:#"VisitorID"]);
NSLog(#"ProfileID : %#",[dictionaryTemp valueForKey:#"ProfileID"]);
NSLog(#"CompanyID : %#",[dictionaryTemp valueForKey:#"CompanyID"]);
NSLog(#"VisitorName : %#",[dictionaryTemp valueForKey:#"VisitorName"]);
}
Now there are good chances that you will get NULL for some keys and it can cause in crash. So avoid those crash by using Null validations.

Parsing values from NSArray based on JSON format

I have a NSArray which is based on JSON format. I requested it from the web and saved it in the array. I am trying to use a dictionary to get the values of "categoryname" and "subscore" and store them in new arrays, but they remain empty. Do I have to convert the array back to NSData using JSON serialisation or is there a more direct way to achieve this?
NSArray detailedscore:
{
"articles": [
{
"abstract": "text",
"title": "title"
}
],
"subscore": 3,
"categoryname": "Reporting"
},
{
"articles": [
{
"abstract": "text2",
"title": "title"
}
],
"subscore": 1,
"categoryname": "Power"
}]
}
Code:
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores addObject:subscore];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
{} ----> means dictionary, []---> array..... this is a rule I follow while assinging the return value from webservices as NSArray or NSDictionary....
Depending on your current JSON format, perhaps this might give you an idea
NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
[categoryArray addObject:[childDict objectForkey:#"categoryname"]];
}
If you have the array use below code
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores score];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
The problem wasn't in the array or dictionary or the web request. I didn't allocated the NSMutableArrays so they were empty all the time. The code works fine for extracting values from the array in case anyone wants to use it.
Hope this helps.
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
NSLog(#"Dict %#",dict);
BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];
if (isValid) {
[target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];
}
else{
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];
}

Import JSON using MagicalRecord [duplicate]

This question already has answers here:
MagicalRecord importFromObject: JSON with dictionary?
(2 answers)
Closed 8 years ago.
I have this JSON document:
[
{
"category": "Para los invitados",
"items": [
{
"title": "Invitaciones",
"subtitle": "Sobres, imprenta",
"items": [
"Invitaciones",
"Sobres",
"Coste envío invitaciones",
"Tarjetas de agradecimiento",
"Sobres para tarjetas de agradecimiento",
"Coste de envío tarjetas de agradecimiento"
]
},
<three elements more...>
]
},
<two elements more...>
]
How can I import this document using MagicalRecord ? Can anyone paste an example ?
Thanks!
If you have finished a Core Data Model and included Magical Record, you can parse the JSON File:
// Your Json File
NSURL *url = [NSURL URLWithString:#"YOUR_JSON"];
NSData* data = [NSData dataWithContentsOfURL: url];
NSError *error; // For later error handling
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Json values for "items" key
NSDictionary *items = [json valueForKey:#"items"];
// We are going through the items
for(int i = 0; i < [items count]; i++) {
// We save the title values into our CoreData Model
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
NSString *title = [[items valueForKey:#"title"] objectAtIndex:i];
YOUR_MODEL_ENTITY *entity = [YOUR_MODEL_ENTITY MR_createInContext:localContext];
entity.title = title;
// We save it
[localContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
if (error) {
NSLog(#"Couldn't save new title with Magical Record: %#", error);
}
}];
}
I hope that it's right, what I wrote...
Please have a look on the documentation :)

Parsing JSON information in Objective C (multiple levels)

I'm able to parse a part of my JSON file but if I want to go deeper in the structure, I'm lost. Here's my JSON :
{
"album":[
{
"album_titre":"Publicité",
"album_photo":"blabla.jpg",
"album_videos":[
{
"titre_video":"Chauffage Compris",
"duree_video":"01'25''",
"photo_video":"chauffage.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2012",
"duree_video":"01'43''",
"photo_video":"nifff.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Events",
"album_photo":"bloublou.jpg",
"album_videos":[
{
"titre_video":"Auvernier Jazz",
"duree_video":"01'15''",
"photo_video":"auvernier.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2011",
"duree_video":"01'03''",
"photo_video":"nifff2011.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Culture",
"album_photo":"bilibl.jpg"
},
{
"album_titre":"Postproduction",
"album_photo":"bizoubzou"
}
]
}
And here's my objective-c code :
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (document==nil)
{
NSLog( #"oops\n%#", error);
}
NSArray *album = document[#"album"];
for( NSDictionary *albumDictionary in album )
{
[album_titre addObject:albumDictionary[#"album_titre"]];
[album_photo addObject:albumDictionary[#"album_photo"]];
for( NSDictionary *album_videosDictionary in albumDictionary[#"album_videos"])
{
[titre_video addObject:album_videosDictionary[#"titre_video"]];
[duree_video addObject:album_videosDictionary[#"duree_video"]];
[photo_video addObject:album_videosDictionary[#"photo_video"]];
[lien_video addObject:album_videosDictionary[#"lien_video"]];
}
}
[self.tableView reloadData];
}
What I can't achieve is to create an array with for example contains all "titre_video" corresponding to "album_titre":"publicité". So it should contain "Chauffage Compris" and "Nifff 2012".
I know it's a kind of easy question but I've search for a while and still not able to do it.
Thank's a lot.
Nicolas
The key is to understand JSON structure:
{ } - - this means the underlying object is a dictionary.
[ ] -- this means the underlyingobject is an array
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
// all titre:video for album_titre:publicite
NSArray *albumArray = [document objectForKey:#"album"];
NSDictionary *dict = [albumArray objectAtindex:0];
NSArray *videos = [dict objectForKey:#"album_videos"];
// to fetch Videos inside album_videos
// here you will get al the videos inside key titre_video
NSMutableArray *titreVideoArray = [[NSMutableArray alloc]init];
for(int i=0; i< videos.count; i++){
NSDictionary *dict = [videos objectAtindex:i];
NSArray *titreVideos = [dict objectForKey:#"titre_video"];
[titreVideoArray addObject: titreVideos];
}
}
It seems you want to fetch all the videos relating to different "album_titre".
I would suggest you to use NSPredicate .
NSArray *videos = [self videosArrayForTitle:#"Publicité" albumArray:albumArray];
Here we pass title and the albumArray from above to fetch us the videos array.
- (NSArray *)videosArrayForTitle:(NSString *)title albumArray:(NSArray *)albumArray{
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"SUBQUERY(album_titre, $content, $content CONTAINS %#).#count > 0", title];
NSArray *searchResults=[albumArray filteredArrayUsingPredicate:resultPredicate];
NSArray *videos = [searchResults objectForKey:#"album_videos"];
return videos;
}
{ } denotes NSDictionary
[ ] denotes NSArray
Copy your json into a text edit file and go in deep. You can use NSLog() to print the data, when you go deep.
Hope it will help you.

Need to generate a JSON document to upload to server after iterating an NSMutableArray of objects with NSString parameters in iOS [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an NSMutableArray that holds a collection of objects, with each object having three parameters of type NSString. What I need to do is iterate through this collection, and create a single JSON document with two subsections: one is called "Test Results", the other is called, "Reports". Each object in the NSMutable array has three NSString parameters, and one of these parameters is called, "testResult".
If "testResult" has a value of either "pass" or "fail", then that object needs to go into the "Test Result" section. If the parameter has a value of "na", then the object goes into the "Reports" section. The "Test Results" section should have three "elements": "Name", "Date", "Test Result". The "Reports" section needs to have only two elements: "Name", and "Date". My issue is not how to iterate through an NSMutableArray using a for loop, my issue is how to iterate through an NSMutableArray, and construct a JSON document as I have described above.
My code would be something like:
//creating beginning of JSON document here
for (Person *personObject in testResultArray) {
if (personObject.testResult == #"na") {
//construct JSON object for "Reports" section
NSString *jsonString1 = personObject.name;
NSString *jsonString2 = personObject.date;
NSData *data1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json1 = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:&error];
id json2 = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:&error];
}
else {
//construct JSON object for "Test Results" section
NSString *jsonString1 = personObject.name;
NSString *jsonString2 = personObject.date;
NSString *jsonString3 = personObject.testResult;
NSData *data1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data3 = [jsonString3 dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json1 = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:&error];
id json2 = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:&error];
id json3 = [NSJSONSerialization JSONObjectWithData:data3 options:0 error:&error];
}
}
//close the JSON document construction, and return JSON document.
Roughly:
//creating beginning of JSON document here
NSMutableArray* reports = [NSMutableArray array];
NSMutableArray* results = [NSMutableArray array];
for (Person *personObject in testResultArray) {
if (personObject.testResult == #"na") {
NSMutableDictionary* naPerson = [NSMutableDictionary dictionary];
[naPerson setObject:personObject.name forKey:#"name"];
[naPerson setObject:personObject.date forKey:#"date"];
[reports addObject:naPerson];
}
else {
NSMutableDictionary* person = [NSMutableDictionary dictionary];
[person setObject:personObject.name forKey:#"name"];
[person setObject:personObject.date forKey:#"date"];
[person setObjeect:personObject.testResult forKey:#"testResult"];
[results addObject:person];
}
}
NSMutableDictionary* mainDoc = [NSMutableDictionary dictionary];
[mainDoc setObject:reports forKey:#"reports"];
[mainDoc setObject:results forKey:#"results"];
NSString* JSONString = [JSONToolKit stringFromObject:mainDoc];
Note that Apple's NSJSONSerialization package is brain-dead, requiring you to uselessly cycle through an NSData representation. Use a different package -- pick one at http://www.json.org/

Resources