一個有料的APP,讀檔這回事在所難免,讀純文字檔還算容易,若這文字檔是
JSON格式
,學問可就多了!
iOS 5.0
之前,
Objective-C
並沒有標準的支援JSON格式的API,如今我們可以直接使用官方的方法,在效能上比第三方套件還要好,這一切都變得很簡單!
JSON全名是
Javascript Object Notation
,是非常light weight而且easy read的一種資料格式,早年常用於Javascript中,等到
RESTFul Web Service
大行其道時,JSON這種輕巧特質的資料格式也跟著被大量應用,目前主流的API
幾乎
都會提供JSON的格式。
現在只要很短的幾行code,就能順利把有著JSON格式的文字檔內容給讀進變數中。
Theme: Read JSON
IDE: Xcode 5
Language: Objective C
Date: 103/03/21
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
// 讀取快樂40週的描述 (json)
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Happy Weeks" ofType:@"txt"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
detailArr = [NSJSONSerialization JSONObjectWithData:fileData options:kNilOptions error:nil];
// 讀取快樂40週的訊息 (txt)
filePath = [[NSBundle mainBundle] pathForResource:@"Happy Messages" ofType:@"txt"];
NSString *fileStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
sharingMessageArr = [fileStr componentsSeparatedByString:@"\r"];
我把檔案放在Resources資料夾中,名叫做Happy Weeks.txt。程式讀出來是個DSData,接著把它轉成JSON物件,通常會用Array或Dictionary去接住資料。
另外一個檔案是Happy Messages.txt,因不是JSON格式,可以把它裝到String中,再做剖析處理。
這裡節錄我檔案中的字串(JSON格式)……
[{“variationID":1,"week":1,"image":"1.jpg","title":"生命的前奏","babyVariation":"寶寶想要吃……","motherVariation":"媽媽變得更美。","nutritionRequirement":"營養要均衡啦。","tips":"這是提示喲~","sharingMessage":"可以分享喲!"},{“variationID":2,"week":2,"image":"2.jpg","title":"生命的前奏","babyVariation":"寶寶想要吃……","motherVariation":"媽媽變得更美。","nutritionRequirement":"營養要均衡啦。","tips":"這是提示喲~","sharingMessage":"可以分享喲!”}]
看起來似乎有點噁心,因為沒有排版,如果想要好觀察字串,可以參考我之前介紹的
JSON線上解析器 (JSON Parser Online)
。它就會變得討人喜愛喲~
"variationID":1,
"week":1,
"image":"1.jpg",
"title":"生命的前奏",
"babyVariation":"寶寶想要吃⋯⋯",
"motherVariation":"媽媽變得更美。",
"nutritionRequirement":"營養要均衡啦。",
"tips":"這是提示喲~",
"sharingMessage":"可以分享喲!"
"variationID":2,
"week":2,
"image":"2.jpg",
"title":"生命的前奏",
"babyVariation":"寶寶想要吃⋯⋯",
"motherVariation":"媽媽變得更美。",
"nutritionRequirement":"營養要均衡啦。",
"tips":"這是提示喲~",
"sharingMessage":"可以分享喲!"
其實原本計劃是從網路上呼叫RESTFul Web Service,來把資料顯示在APP上,現在變成要內建於APP中⋯⋯因為多變的客戶,讓工程師多才多藝XD~
註:第三方套件與官方套件相關
[SBJSON (json-framework)] (
http://code.google.com/p/json-framework/
)
[TouchJSON (from touchcode)] (
http://code.google.com/p/touchcode/
)
[YAJL (objective-C bindings)] (
http://github.com/gabriel/yajl-objc
)
[JSONKit] (
https://github.com/johnezang/JSONKit
)
[NextiveJson] (
https://github.com/nextive/NextiveJson
)
[NSJSONSerialization](
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946
)
參考:
iOS V.S JSON
、
iOS5系統API和5個開源庫的JSON解析速度測試
、
REST and RESTfull web service
、WiKi –
REST
。
HappyMan・迴響