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下的详细说明。