2013-04-05 58 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