2013-08-29 14 views
39

JSONファイルからデータを解析しようとしています。私は、ラベルを持つUIViewに、またはWebViewで、その解析/フェッチされたデータを配置しようとしています。 はJSONファイルは、以下のようになります。iOSのファイルからJSONを解析するにはどうすればよいですか?

{"bodytext": "<p>\n Some lines here about some webpage (&ldquo; <em>Site</>&rdquo;) some more lines here. \n </p>\n\n <p>\n some more stuff here </p> 
} 

ありWebのURLから取得したJSONを解析する方法を示すスタックオーバーフローのここでの記事がありますが、私は実際にはすでに、私が解析したいJSONファイルを持っています。 JSONをファイルから解析するにはどうすればよいですか?

+0

jsonファイルをhtmlファイルにしました。それを読んでウェブビューに表示しました。もし誰かがこれをやるより良い方法を持っているなら、私にコメントして教えてください。 – Chris

答えて

110
  1. 空のテキストファイル(新規ファイル/その他/空)を作成します。 "example.json"

  2. ファイルにjson文字列を貼り付けます。

  3. データを取得するためにこれらの行を使用します。

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"]; 
    NSData *data = [NSData dataWithContentsOfFile:filePath]; 
    NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 
    
+11

最後の月に100回以上貼り付けられたこのスニペットをコピーします – lucaslt89

+1

@ lucaslt89 Xcodeスニペットにする時間:http://nshipster.com/xcode-snippets/ – Kheldar

+0

または多分ヘルパークラス/カテゴリ –

7

私はこれを踏襲しているし、それが受け入れ答えの罰金

NSError *error = nil; 
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"messages" 
                 ofType:@"json"]; 
NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath]; 
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:dataFromFile 
                 options:kNilOptions 
                 error:&error]; 
if (error != nil) { 
    NSLog(@"Error: was not able to load messages."); 
    return nil; 
} 
17

スウィフト2.0バージョン取り組んでいる:

if let filePath = NSBundle.mainBundle().pathForResource("example", ofType: "json"), data = NSData(contentsOfFile: filePath) { 
     do { 
      let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) 
     } 
     catch { 
      //Handle error 
     } 
    } 
関連する問題