Import JSON using MagicalRecord [duplicate] - ios

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

Related

Parse JSON response string in Objective - C [duplicate]

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

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

json iOS parsing error

I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:#"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:#"test"];
NSLog(#"%#",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog? Each method I've tried has resulted in the application crashing.
Test is an array:
NSArray *test = [dataDictionary objectForKey:#"test"];
NSLog(#"test =%#", test);
for(NSDictionary *coordinates in test){
NSLog(#"id = %#", coordinates[#"id"]);
NSLog(#"lat = %#", coordinates[#"lat"]);
NSLog(#"long = %#", coordinates[#"long"]);
}
NSArray *array = [dataDictionary valueForKey:#"test"];
for(int i = 0; i < array.count; i++){
NSLog(#"%#", [array[i] valueForKey:#"name"]);
}
like that u can get NSLog whatever key you want
for id
NSLog(#"%#", [array[i] valueForKey:#"id"]);
for lat
NSLog(#"%#", [array[i] valueForKey:#"lat"]);
and so on.....
Happy coding

parsing JSON values from JSON Array in iOS

i am getting the response from the server in JSON array form like below :
{
"status": "success",
"data": [
{
"auth_Secret_ticket_refresh": "NULL",
"userId": "10632",
"loginEmail": "Raushan#gmail.com",
"auth_authorizationCode": "4cb8c5e8a7f5",
"accountType": "flickr",
"auth_Token": "23104658-d2e65d5f94554652",
"userName": "betterlabpune",
"auth_subdomain": "NULL"
},
{
"auth_Secret_ticket_refresh": "NULL",
"userId": "19629",
"loginEmail": "Ipad#gmail.com",
"auth_authorizationCode": "8b909cb3e0e1",
"accountType": "flickr",
"auth_Token": "77645323118718-bac668bc2b95ad89",
"userName": "betterlabpune",
"auth_subdomain": "NULL"
}
]
}
I want to extract the value from JSON array for the 0 index, value for "userId" and "userName".
i had tried to extract values in many ways ,below is my code:
NSMutableData * _responseData = [[NSMutableData alloc]init];
[_responseData appendData:data];
NSJSONSerialization *dataAsString=(NSJSONSerialization*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// dataJson=(NSDictionary*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data in register reponse : %#",dataAsString);
NSJSONSerialization *json;
NSDictionary *dataJson;
NSError *error;
NSDictionary *JSONE = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
NSLog(#"JSONE : %#",JSONE);
json=[NSJSONSerialization JSONObjectWithData:_responseData
options:NSJSONReadingMutableLeaves
error:&error];
[self processData:dataJson];
dataJson=[[NSDictionary alloc]init];
dataJson=(NSDictionary *)json;
NSString * status=[dataJson objectForKey:#"status"];
NSString * message=[[dataJson objectForKey:#"data"]objectForKey:#"id"];
NSLog(#"status : %#",status);
NSLog(#"message: %#",message);
NSMutableArray *argsArray = [[NSMutableArray alloc] init];
argsArray= [dataJson valueForKeyPath:#"status"];
NSLog(#" client Id : %#", [argsArray objectAtIndex:0]);
bet every time i get null in my result.
Please help me out.
Thank you for your precious time.
try this...
if ([[dataJson valueForKey:#"status"]isEqualToString:#"success"])
{
NSMutableArray *tempArray=[NSMutableArray array];
for (NSDictionary *tempDic in [dataJson valueForKey:#"data"])
{
[tempArray addObject:[tempDic valueForKey:#"userId"]];
}
NSLog(#"%#",tempArray);
}

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.

Resources