你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS開發之——使用SBJson拼接Json字符串

IOS開發之——使用SBJson拼接Json字符串

編輯:IOS開發綜合

SBJson包的下載地址在上一篇文章中。

可以使用NSDictionary中的鍵值對來拼接Json數據,非常方便,也可以進行嵌套,直接上代碼:

    //開始拼接Json字符串
    NSDictionary *dataDictionary= [NSDictionary dictionaryWithObjectsAndKeys:@"mac",@"mac",
                                   @"game",@"game",
                                   @"devicetoken",@"devicetoken",
                                   @"device",@"device",
                                   @"gv",@"gv",
                                   @"lang",@"lang",
                                   @"os",@"os",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 *jasonString = [writer stringWithObject:jsonDictionary];
    NSLog(@"%@",jasonString);

上面的代碼用到了三層嵌套,注意的是,NSDictionary中,前面的是值,後面的是鍵。

拼接後的結果如下:

{"pv":"pv","param":{"act":"getSession","data":{"os":"os","mac":"mac","game":"game","gv":"gv","lang":"lang","devicetoken":"devicetoken","device":"device"}}}

使用Json在線校驗工具解析後:

{
    "pv": "pv",
    "param": {
        "act": "getSession",
        "data": {
            "os": "os",
            "mac": "mac",
            "game": "game",
            "gv": "gv",
            "lang": "lang",
            "devicetoken": "devicetoken",
            "device": "device"
        }
    }
}


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved