是否有任何通用的實現將任何對象轉換爲NSDictionary,將所有變量名稱設置爲鍵和值作爲字典值?將對象轉換爲NSDictionary
回答
使用SBJSONParser求解,將NSObject轉換爲JSON表示形式,然後將NSDictionary從中提取出來。
你可以告訴我一個例子,我試圖將一個NSobject轉換爲json,發現沒有好的例子可以讓你給我一個鏈接? – Radu 2011-07-27 12:43:34
http://code.google.com/p/json-framework/source/browse/trunk/Source/NSObject%2BSBJSON.m?r=532 – 2011-07-28 04:13:11
如果你使用JSONKit,你會做NSDictionary * deserializedData = [jsonString objectFromJSONString ]。 – loretoparisi 2012-07-14 00:29:57
不,你可以在你的課堂中擁有一切,例如對其他對象和原語的引用。 NS-Dictionary可以將自己序列化爲NSString,NSString可以從字符串重新創建字典。最好將你提供你自己的方法來序列化它。
爲了實現您的目標,您可以使用鍵值編碼。此協議提供了一種機制,可根據以NSString表示的屬性名稱來設置對象屬性的值,而不是直接調用訪問器。
爲了使其工作,您需要使用遵循命名約定的訪問器定義對象(使用屬性足夠簡單)。你可以看到的NSKeyValueCoding協議蒞臨指導:
和鍵 - 值編碼編程指南這裏:
你還要做迭代,但它是一個好的開始。
做到這一點的最佳方法是使用一個庫序列化/反序列化 許多圖書館也有,但我喜歡的是 JagPropertyConverter https://github.com/jagill/JAGPropertyConverter
它可以將您的自定義對象轉換爲NSDictionary中,反之亦然
假設
@interface Person : NSObject
@property (nonatomic, retain) NSNumber * age
@property (nonatomic, retain) NSString * address
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * cellNo;
@end
JAGPropertyConverter *converter = [[JAGPropertyConverter alloc]init];
converter.classesToConvert = [NSSet setWithObjects:[Person class], nil];
Person *person = [[Person alloc]init];
person.name = @"name";
person.address = @"address";
person.age = @27;
person.cellNo = @"XXXXXXXXXX";
//For Object to Dictionary
NSDictionary *dictPerson = [converter convertToDictionary:person];
//For Dictionary to Object
Person *person = [[Person alloc]init];
[converter setPropertiesOf:person fromDictionary:dictPerson];
- 1. 如何將NSDictionary轉換爲JSON對象?
- 2. 將NSDictionary對象轉換爲自定義複雜對象
- 3. 將NSDictionary對象轉換爲NSData對象,反之亦然
- 4. 轉換一個NSDictionary對象到對象
- 5. 將NSDictionary字符串轉換爲NSDictionary
- 6. 將NSObject轉換爲NSDictionary
- 7. 將NSArray轉換爲NSDictionary
- 8. 將NSDictionary轉換爲XML
- 9. 將NSDictionary轉換爲std :: vector
- 10. 將NSDictionary轉換爲NSString
- 11. 將NSDictionary轉換爲UITableView
- 12. 將NSDictionary轉換爲JSON
- 13. 將NSDictionary轉換爲NSArray
- 14. 將NSData轉換爲NSDictionary
- 15. 將nsdictionary轉換爲nsdata
- 16. 將NSDictionary值轉換爲NSString
- 17. 將NSString轉換爲NSDictionary
- 18. 如何使用JavaScriptCore將JavaScript對象轉換爲NSDictionary
- 19. 如何將一個類對象轉換爲一個NSDictionary?
- 20. 如何利用NSCoding將對象轉換爲NSDictionary?
- 21. AFNetworking GET請求 - 無法將響應對象轉換爲NSDictionary
- 22. 將NSData對象轉換爲NSDictionary的問題
- 23. 將包含NSDictionary對象的NSArray轉換爲IOS中的單個NSDictionary
- 24. 將對象轉換爲xml
- 25. 將對象轉換爲KeyValuePair
- 26. 將對象轉換爲CLOB
- 27. 將DataTable轉換爲對象[,]
- 28. 將對象轉換爲DateRange
- 29. 將流轉換爲對象?
- 30. 將對象轉換爲NameValueCollection
看到這個答案將對象轉換爲NSDictionary的 [轉換物體插入的NSDictionary] [1] [1]:http://stackoverflow.com/a/12890495/600076 – iHS 2012-10-15 06:53:27
這是最好的動態的方式,我發現http://stackoverflow.com/questions/ 10318366/obj-c-easy-method-to-convert-from-nsobject-with-properties-to-nsdictionary#10318659 – 2013-03-31 13:29:43