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下的具体说明。
时间: 2024-10-07 08:48:40