2013-08-29 93 views
39

Tôi đang cố gắng phân tích dữ liệu từ tệp JSON. Tôi đang cố gắng đưa dữ liệu được phân tích/tìm nạp đó vào UIView bằng nhãn hoặc trong chế độ xem web. Các tệp JSON trông giống như sau:Làm cách nào để phân tích cú pháp JSON từ một tệp trong iOS?

{"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> 
} 

Có bài viết ở đây trên Stack Overflow cho thấy làm thế nào để phân tích cú pháp JSON lấy ra từ một URL Web, nhưng tôi thực sự đã có một tệp JSON Tôi muốn phân tích. Làm cách nào để phân tích cú pháp JSON từ một tệp?

+0

Chỉ cần tạo tệp json thành tệp html d đọc nó và hiển thị nó trên màn hình web. Nếu có ai có cách làm tốt hơn, hãy bình luận và cho tôi biết. – Chris

Trả lời

110
  1. Tạo tệp văn bản trống (Tệp mới/Khác/trống), ví dụ: "example.json"

  2. Dán chuỗi json vào tệp.

  3. Sử dụng những dòng này để lấy dữ liệu:

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

Tôi đã sao chép đoạn trích này hơn 100 lần trong tháng trước – lucaslt89

+1

@ lucaslt89 thời gian để tạo đoạn mã Xcode: http://nshipster.com/xcode-snippets/ – Kheldar

+0

hoặc có thể một số lớp/danh mục trợ giúp –

7

Tôi đã theo này và nó đang làm việc tốt

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

Swift phiên bản 2.0 của câu trả lời được chấp nhận:

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