2011-08-17 98 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。 –