標籤:json iphone ios jsonmodel mjextension
iOS下JSON字串還原序列化成對象,在正式的項目中比較常見。如下幾個常用開源庫,可以根據個人喜好任選其一:
1. JSONModel: https://github.com/icanzilb/JSONModel
2. MJExtension: https://github.com/CoderMJLee/MJExtension
3. Mantle: https://github.com/Mantle/Mantle
其中,JSONModel對數組元素還原序列化,需要定義一個跟數組元素Model的類名相同的@protocol
{ "order_id": 104, "total_price": 103.45, "products" : [ { "id": "123", "name": "Product #1", "price": 12.95 }, { "id": "137", "name": "Product #2", "price": 82.95 } ]}
@protocol ProductModel@end@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString* name;@property (assign, nonatomic) float price;@end@implementation ProductModel@end@interface OrderModel : JSONModel@property (assign, nonatomic) int order_id;@property (assign, nonatomic) float total_price;@property (strong, nonatomic) NSArray<ProductModel, ConvertOnDemand>* products;@end@implementation OrderModel@end
MJExtension號稱“世界上轉換速度最快、使用最簡單方便的字典轉模型架構”,有興趣的可以看github下的具體說明。
iOS下JSON還原序列化開源庫