2013-04-05 103 views
0

我是新來Objective-C和iOS開發,並試圖編寫一個方法來生成一個JSON字符串,但是當我NSLog這個我得到一堆十六進制代碼(我猜他們是指針地址)可以有人看這個方法,並告訴我我做錯了..從NSMutableDictionary生成JSON

-(NSData *)generateInputJSON 
{ 

    NSError* error = nil; 

    NSString* region = [[NSLocale currentLocale]localeIdentifier]; 

    NSString* language = [[NSLocale preferredLanguages]objectAtIndex:0]; 

    NSMutableDictionary* properties = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
           _sphereODNumber,@"sphereOD", 
           _sphereOSNumber,@"sphereOS", 
           _cylinderODNumber,@"cylinderOD", 
           _cylinderOSNumber,@"cylinderOS", 
           _visionCorrection,@"visionCorrection", 
             region,@"region", 
             language,@"language", 
           nil]; 

    if([_visionCorrection isEqualToString:@"multiFocal"] || 
     [_visionCorrection isEqualToString: @"progressive"]) 
    { 
     [properties setValue:_addODNumber forKey:@"addOD"]; 
     [properties setValue:_addOSNumber forKey:@"addOS"]; 
    } 


    if([_visionCorrection isEqualToString: @"progressive"]) 
    { 
     [properties setValue:_fittingHeightNumber forKeyPath:@"fittingHeight"]; 
    } 

    NSData* inputJSON = [NSJSONSerialization dataWithJSONObject:properties options:NSJSONWritingPrettyPrinted error:&error]; 

    return inputJSON; 
} 

我數收益:

< 7b0a2020 226c616e 67756167 6522203a 2022656e 222c0a20 20227669 73696f6e 436f7272 65637469 6f6e2220 3a202270 726f6772 65737369 7665222c 0a202022 6164644f 4422203a 20342e35 2c0a2020 22616464 4f532220 3a20342e 352c0a20 20227370 6865726 5 4f532220 3a20342e 352c0a20 20227265 67696f6e 22203a20 22656e5f 5553222c 0a202022 63796c69 6e646572 4f532220 3a20342e 352c0a20 20226669 7474696e 67486569 67687422 203a2031 372c0a20 20227370 68657265 4f442220 3a20342e 352c0a20 20226379 6c696e64 65724f44 22203a20 342e350a 7D>

回答

1

打印你看到的是NSData對象的描述,這僅僅是在字節數據以十六進制表示。如果你要(比如說)將這些數據寫入文件並用文本編輯器打開文件,那麼實際上你會看到你想要的字符串。既然你想從你的函數返回一個字符串,可以NSData的轉換爲字符串,像這樣:

return [[NSString alloc] initWithData:inputJSON encoding:NSUTF8StringEncoding]; 

記住自動釋放,如果你在非ARC代碼是。如果要返回字符串,還應該將方法的返回類型從NSData*更改爲NSString*

1

將數據轉換成一個NSString像這樣

NSString *string = [[NSString alloc]initWithData:inputJSON encoding:NSUTF8StringEncoding]; 

然後只需用的NSLog

NSLog(@"%@", string); 
+0

問題真的對你們兩個...當我把這個JSON傳遞給服務器時,是否需要轉換爲正確編碼的字符串,或者NSData爲 – erik 2013-04-05 17:11:13

+0

不是,應該可以通過'NSData' ,您只需要在http調用中設置正確的編碼,以便服務器知道它正在接收UTF8數據 – iain 2013-04-05 17:12:49