與伺服器溝通時,兩端約定的資料格式往往有巢狀層次。手動拼字串容易漏引號、少逗號,實務上更穩健的做法是「用 NSDictionary 描述結構,再交給工具序列化」。本文整理 SBJson 的解析與拼接用法。
專案下載位置:https://stig.github.com/json-framework/
NSData *responseData = [response responseData]; NSString *strResponser = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; SBJsonParser *parser = [[SBJsonParser alloc] init]; NSMutableDictionary *dicMessageInfo = [parser objectWithString:strResponser]; [parser release]; NSString *sender = [dicMessageInfo objectForKey:@"sender"];
NSString *dataStr = @"{\"cross\":{\"1\":\"true\",\"2\":\"false\",\"3\":\"true\"}}";
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicMessageInfo = [parser objectWithString:strResponser];
// 逐層取出
NSMutableDictionary *cross = [dicMessageInfo objectForKey:@"cross"];
NSString *cross1 = [cross objectForKey:@"1"];
[parser release];
NSLog(@"cross1: %@", cross1);
SBJson 的 SBJsonWriter 提供了 - (NSString *)stringWithObject:(id)value,可以把符合 key/value 結構的 NSDictionary 直接格式化為 JSON 字串;其他資料則用 NSMutableString 的 appendString: 與 appendFormat: 動態組裝。
- (NSString *)getJsonString {
NSMutableString *json = [NSMutableString stringWithCapacity:128];
NSString *jsonString = nil;
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
[json appendString:@"{\"data\":{"];
[json appendFormat:@"\"%@\":\"%d\",", @"reset", reset];
if (missionStatus != NULL) {
jsonString = [writer stringWithObject:status];
if (jsonString != NULL) {
[json appendString:@"\"status\":"];
[json appendString:jsonString];
}
}
[json appendString:@"}}"];
return json;
}
拼完的字串可以丟到 https://jsonlint.com/ 做線上格式驗證,能快速定位少了哪個引號或逗號。
既然 SBJsonWriter 能處理任意巢狀的 dictionary/array,就沒有必要冒著格式錯誤的風險去手動串接:
NSDictionary *dataDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
mac, @"mac",
game, @"game",
devicetoken, @"devicetoken",
device, @"device",
gv, @"gv",
lang, @"lang",
os, @"os",
hardware, @"hardware",
down, @"down", nil];
NSDictionary *parmDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"getSession", @"act",
dataDictionary, @"data", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
pv, @"pv",
parmDictionary, @"param", nil];
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:jsonDictionary];
NSLog(@"%@", jsonString);
這樣寫的優點很明顯:結構一目了然,引號與逗號完全不用操心,要增減欄位也只是改字典內容。
https://jsonlint.com/ —— 貼上字串即可檢查格式並格式化輸出,除錯時非常好用。
dictionaryWithObjectsAndKeys: 的參數是「值、鍵、值、鍵…」交替,且必須以 nil 結尾;若某個值本身為 nil 會直接提早終止,導致後面的鍵值全部遺失,實務上建議改用 NSDictionary 的字典字面語法 @{@"key": value} 並先過濾 nil。NSJSONSerialization,API 能力相當且無需外部依賴。"1" 與數字 1 在嚴格解析的後端眼中是兩回事)。