2011-08-17 96 views
0

有什么办法让NSLog打印出一个完整的JSON文件。我现在说Xcode如何NSLog一个JSON

NSString *deviceInfo = [NSString stringWithFormat:@"%@ %@", 
         [[UIDevice currentDevice]model], [[UIDevice currentDevice]systemVersion]]; 
NSDictionary *json = [deviceInfo JSONValue]; 
NSLog(@"json file = %@", json); 

而且它打印出“JSON文件=(空)”

感谢 克林顿

回答

3

我想你误会什么JSON是。您传递给-JSONValue的字符串不是有效的JSON字符串,因此它返回nil。你还不如干脆构建字典自己:

UIDevice *device = [UIDevice currentDevice]; 
NSDictionary *deviceInfo = [NSDictionary dictionaryWithObjectsAndKeys:[device model], @"deviceModel", [device systemVersion], @"deviceSystemVersion", nil]; 

然后,如果你希望对象的JSON字符串表示(用于发送到您的服务器,例如):

NSString *jsonDeviceInfo = [deviceInfo JSONRepresentation]; 
+0

非常感谢你的工作。它目前正在打印出这个'{“deviceModel”:“iPod touch”,“deviceSystemVersion”:“4.3.5”},如果我想在每个硬件外部有多个块和某些东西, :{“deviceModel”:“iPod touch”}“os”:{“deviceSystemVersion”:“4.3.5”}'我该怎么做。 –

+0

只要嵌套字典。 '[NSDictionary dictionaryWithObjectsAndKeys:someDictionary,@“someKey”,someOtherDictionary,@“someOtherKey”,零]' –

+0

是的工作。还有一件事是。我似乎无法改变NSDictionary中的顺序。我有'NSDictionary * fullJSON = [NSDictionary dictionaryWithObjectsAndKeys:hardware,@“hw”,os,@“os”,nil];'但是它打印出了{{{“os”:{“ver”:“4.3.5” },“hw”:{“model”:“iPod touch”}}'我不认为它是必要的,但如果我能够使硬件成为第一,那将会很好。 –

1

你确定你的代码可以正常工作?你的NSDictionary似乎是零...

你可以请发布的JSONValue的实施?

如果按照预期你总是可以通过扩展覆盖-(NSString *) description方法的对象不打印,它会打印你是如何规定的:)

+0

我想'的NSLog( @“json file =%@”,[json description]);'并且我仍然收到(null)。此外,JSONValue似乎也有错误。它说'-JSONValue失败。错误跟踪是:( “错误域= org.brautaset.JSON.ErrorDomain代码= 3”无法识别的前导字符\“UserInfo = 0x1cc3c0 {NSLocalizedDescription =无法识别的前导字符}”'我不知道你的意思是什么 –

+1

NSString没有实现一个名为JSONValue afaik的方法,所以你必须自己实现它吗? JSONValue { SBJsonParser * jsonParser = [SBJsonParser新]; ID再版= [jsonParser objectWithString:自我];(!再版) 如果 的NSLog(@ “ - JSONValue失败的错误跟踪:%@”,[jsonParser errorTrace ]); [jsonParser release]; return repr; }' – Julian

+0

JSONValue来自JSON库,它看起来像这个' - (id)的JSONValue。 –