您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 中用 SBJson 完成 JSON 的拼接與解析(含巢狀結構)

編輯:iOS 技巧大全

與伺服器溝通時,兩端約定的資料格式往往有巢狀層次。手動拼字串容易漏引號、少逗號,實務上更穩健的做法是「用 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);

三、拼接 JSON 字串

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/ 做線上格式驗證,能快速定位少了哪個引號或逗號。

四、更好的做法:用多層 NSDictionary 取代手拼

既然 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 在嚴格解析的後端眼中是兩回事)。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved