'NSDictionary에'에 해당되는 글 1건

  1. 2010.10.12 JSON을 NSArray나 NSDictionary에 넣는 방법
아이폰어플개발정보2010. 10. 12. 03:59
JSON을 NSArray나 NSDictionary에 넣는 방법

In this project we will be using very useful set of libraries from the json-framework project which is an open-source project available for free on the internet.

Please download source files for JSON framework library project here:

http://code.google.com/p/json-framework/

or you can download and open the example projech available on this page and copy those source files from this project. Files are located Classes/JSON/ folder in this example.

Don't even try to use the framework which is located in the original project on Google Code as any thirdparty framework is not permitted on iPhone platform.

Ok, let's assume you've created a new for example Navigation or Window based project, and you have the neccessary libraries already included in it. Try to build the project (you can use the Cmd + B shortcut) to see that everything is allright and we can move on to the more interesting part.

Now you have to declare IBOutlet for your textview (UITextView) and your buttons (UIButton) IBAction that will carry all the functionality after pressing the button.

  1. IBOutlet UITextView *logWindow;  

And

  1. // our text field window
  2. @property (nonatomic, retain) IBOutlet UITextView *logWindow;  
  3. // action we'll use after pressing the button to start parsing the file
  4. - (IBAction)startParser:(UIButton *)sender;  

the entire source code for your controller's header file (.h) is here:

  1. //
  2. //  TutorialProjectViewController.h
  3. //  TutorialProject
  4. //
  5. //  Created by Ondrej Rafaj on 5.8.09.
  6. //  Copyright Home 2009. All rights reserved.
  7. //
  8. #import 
  9. #import "SBJSON.h"
  10. @interface TutorialProjectViewController : UIViewController {  
  11.     // ------ Tutorial code starts here ------
  12.     // our text field window
  13.     IBOutlet UITextView *logWindow;  
  14.     // ------ Tutorial code ends here ------
  15. }  
  16. // ------ Tutorial code starts here ------
  17. // our text field window
  18. @property (nonatomic, retain) IBOutlet UITextView *logWindow;  
  19. // action we'll use after pressing the button to start parsing the file
  20. - (IBAction)startParser:(UIButton *)sender;  
  21. // ------ Tutorial code ends here ------
  22. // This function is for button which takes you to the xprogress.com website
  23. - (IBAction) runXprogressComButton: (id) sender;  
  24. @end  

Now we have to edit the .m file. First synthesize the logWindow variable:

  1. @synthesize logWindow;  

and than, don't forget to release this variable in the dealloc function:

  1. [logWindow release];  

Start the IBAction for your button which is called startParser:

  1. - (IBAction)startParser:(UIButton *)sender {  
  2. }  

And start coding :)

You have to find your file in the application bundle (I'll show you how to load this file properly from the internet next time, today you have to inlude the json file into your resources folder), I assume that the json file is called data.json. We will be using just some random jsom file I found on the internet, content looks like that:

  1. {  
  2.     "menu": {  
  3.         "header""xProgress SVG Viewer",  
  4.         "items": [  
  5.             {  
  6.                 "id""Open"
  7.             },  
  8.             {  
  9.                 "id""OpenNew",  
  10.                 "label""Open New"
  11.             },  
  12.             null,  
  13.             {  
  14.                 "id""ZoomIn",  
  15.                 "label""Zoom In"
  16.             },  
  17.             {  
  18.                 "id""ZoomOut",  
  19.                 "label""Zoom Out"
  20.             },  
  21.             {  
  22.                 "id""OriginalView",  
  23.                 "label""Original View"
  24.             },  
  25.             null,  
  26.             {  
  27.                 "id""Quality"
  28.             },  
  29.             {  
  30.                 "id""Pause"
  31.             },  
  32.             {  
  33.                 "id""Mute"
  34.             },  
  35.             null,  
  36.             {  
  37.                 "id""Find",  
  38.                 "label""Find..."
  39.             },  
  40.             {  
  41.                 "id""FindAgain",  
  42.                 "label""Find Again"
  43.             },  
  44.             {  
  45.                 "id""Copy"
  46.             },  
  47.             {  
  48.                 "id""CopyAgain",  
  49.                 "label""Copy Again"
  50.             },  
  51.             {  
  52.                 "id""CopySVG",  
  53.                 "label""Copy SVG"
  54.             },  
  55.             {  
  56.                 "id""ViewSVG",  
  57.                 "label""View SVG"
  58.             },  
  59.             {  
  60.                 "id""ViewSource",  
  61.                 "label""View Source"
  62.             },  
  63.             {  
  64.                 "id""SaveAs",  
  65.                 "label""Save As"
  66.             },  
  67.             null,  
  68.             {  
  69.                 "id""Help"
  70.             },  
  71.             {  
  72.                 "id""About",  
  73.                 "label""About xProgress CVG Viewer..."
  74.             }   
  75.         ]  
  76.     }  
  77. }  

You can create new file by right-clicking the Resources folder and selecting Add -> New file -> Other (Under Mac OS X) -> Empty file. The XML equivalent will look like that:

  1.   
  2.      xProgress Viewer  
  3.     "Open" id="Open">Open  
  4.     "OpenNew" id="OpenNew">Open New  
  5.     "ZoomIn" id="ZoomIn">Zoom In  
  6.     "ZoomOut" id="ZoomOut">Zoom Out  
  7.     "OriginalView" id="OriginalView">Original View  
  8.     "Quality" id="Quality">Quality  
  9.     "Pause" id="Pause">Pause  
  10.     "Mute" id="Mute">Mute  
  11.     "Find" id="Find">Find...  
  12.     "FindAgain" id="FindAgain">Find Again  
  13.     "Copy" id="Copy">Copy  
  14.     "CopyAgain" id="CopyAgain">Copy Again  
  15.     "CopySVG" id="CopySVG">Copy SVG  
  16.     "ViewSVG" id="ViewSVG">View SVG  
  17.     "ViewSource" id="ViewSource">View Source  
  18.     "SaveAs" id="SaveAs">Save As  
  19.     "Help" id="Help">Help  
  20.     "About" id="About">About xProgress Viewer...  
  21.   

Ok, now we are going to get the path to the file data.json:

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];  

Than you have to load contents of this file:

  1. NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];  

Allocate new instance of your json parser:

  1. SBJSON *parser = [[SBJSON alloc] init];  

And parse the first level of the file:

  1. NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];  
  2. // getting the data from inside of "menu"
  3. NSDictionary *menu = (NSDictionary *) [data objectForKey:@"menu"];  

NSDictionary is something like an array, which has numeric keys but you can use for example strings as a key.

This new NSDictionary is taken from the data dictionary by selecting the only key on this level, which is menu [data objectForKey:@"menu"].

Now we can get some more data , like the content of header as a string (NSString):

  1. NSString *header = (NSString *) [menu objectForKey:@"header"];  

And an array that is in the json file enclosed into the square brackets.

  1. NSArray *items = (NSArray *) [menu objectForKey:@"items"];  

Now you want to go trough the array and do something with the data init. You can do something like that:

  1. for (id *item in items) {  
  2.         // if the item is NSDictionary (in this case ... different json file will probably have a different class)
  3.         NSLog(@"One item: %@", [NSString stringWithFormat:@"Item -> %@", (NSDictionary *) item]);  
  4. }  

On the end of the function don't forget to release the json data parser:

[parser release];

This file in the example is slightly different as I've used a separated function to add results into the UITextView we've created earlier.

This function is not doing anything else than adding new records on the top of the logWindow:

  1. - (void)addRowToLogWindow:(id)data {  
  2.     logWindow.text = [NSString stringWithFormat:@"Adding data: %@  
  3. %@", data, logWindow.text]; // adding new row + 2x new line "
  4. "  
  5. }  

Code for the entire .m file is here:

  1. //
  2. //  TutorialProjectViewController.m
  3. //  TutorialProject
  4. //
  5. //  Created by Ondrej Rafaj on 5.8.09.
  6. //  Copyright Home 2009. All rights reserved.
  7. //
  8. #import "TutorialProjectViewController.h"
  9. @implementation TutorialProjectViewController  
  10. // ------ Tutorial code starts here ------
  11. @synthesize logWindow;  
  12. // function for adding an 
  13. - (void)addRowToLogWindow:(id)data {  
  14.     logWindow.text = [NSString stringWithFormat:@"Adding data: %@  
  15. %@", data, logWindow.text]; // adding new row + 2x new line "
  16. "  
  17. }  
  18. - (IBAction)startParser:(UIButton *)sender {  
  19.     // getting path to the file
  20.     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];  
  21.     NSLog(@"Path: %@", filePath);  
  22.     // reading content of the file, don't use the [NSString stringWithContentsOfFile:@"/Your/Filepath/"]; as this is deprecated since iPhone SDK 3.0
  23.     NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];  
  24.     //NSLog(@"File content: %@", fileContent);
  25.     // creating new parser
  26.     SBJSON *parser = [[SBJSON alloc] init];  
  27.     // parsing the first level
  28.     NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];  
  29.     // getting the data from inside of "menu"
  30.     NSDictionary *menu = (NSDictionary *) [data objectForKey:@"menu"];  
  31.     // getting the first value which is stored in the header
  32.     NSString *header = (NSString *) [menu objectForKey:@"header"];  
  33.     [self addRowToLogWindow:[NSString stringWithFormat:@"Header -> %@", header]];  
  34.     // parsing all the items in to the NSArray
  35.     NSArray *items = (NSArray *) [menu objectForKey:@"items"];  
  36.     // reading all the items in the array one by one
  37.     for (id *item in items) {  
  38.         // if the item is NSDictionary (in this case ... different json file will probably have a different class)
  39.         [self addRowToLogWindow:[NSString stringWithFormat:@"Item -> %@", (NSDictionary *) item]];  
  40.     }  
  41.     for (id *item in items) {  
  42.         // if the item is NSDictionary (in this case ... different json file will probably have a different class)
  43.         NSLog(@"One item: %@", [NSString stringWithFormat:@"Item -> %@", (NSDictionary *) item]);  
  44.     }  
  45.     // releasing parser
  46.     [parser release];  
  47. }  
  48. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  49. - (void)viewDidLoad {  
  50.     // removing the default data from our UITextView
  51.     logWindow.text = @"";  
  52.     [super viewDidLoad];  
  53. }  
  54. // ------ Tutorial code ends here ------
  55. /* 
  56. // The designated initializer. Override to perform setup that is required before the view is loaded. 
  57. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
  58.     if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { 
  59.         // Custom initialization 
  60.     } 
  61.     return self; 
  62. } 
  63. */
  64. /* 
  65. // Implement loadView to create a view hierarchy programmatically, without using a nib. 
  66. - (void)loadView { 
  67. } 
  68. */
  69. /* 
  70. // Override to allow orientations other than the default portrait orientation. 
  71. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
  72.     // Return YES for supported orientations 
  73.     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
  74. } 
  75. */
  76. - (void)didReceiveMemoryWarning {  
  77.     // Releases the view if it doesn't have a superview.
  78.     [super didReceiveMemoryWarning];  
  79.     // Release any cached data, images, etc that aren't in use.
  80. }  
  81. - (void)viewDidUnload {  
  82.     // Release any retained subviews of the main view.
  83.     // e.g. self.myOutlet = nil;
  84. }  
  85. // This function is for button which takes you to the xprogress.com website
  86. - (IBAction) runXprogressComButton: (id) sender {  
  87.     NSURL *url = [[[NSURL alloc] initWithString: @"http://www.xprogress.com/"] autorelease];  
  88.     [[UIApplication sharedApplication] openURL:url];  
  89. }  
  90. - (void)dealloc {  
  91.     // ------ Tutorial code starts here ------
  92.     [logWindow release];  
  93.     // ------ Tutorial code ends here ------
  94.     [super dealloc];  
  95. }  
  96. @end  

Now you have to connect your button and textview in Interface Builder to the IBAction for the button and logWindow outlet to the UITextView.

Now you can try to run the application and see if the data are parsed properly into the logWindow.

http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/

Posted by 오늘마감

댓글을 달아 주세요