假设我有这个模型。
@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>* products;
@end
@implementation OrderModel
@end
问题:
然后我如何生成以下JSON。
“产品”:[ { “id”:“123”, “名称”:“产品#1”, “价格”:12.95 }, { “id”:“137”, “名称”:“产品#2”, “价格”:82.95 } ]
或整个对象。
{
"order_id": 104,
"total_price": 103.45,
"products" : [
{
"id": "123",
"name": "Product #1",
"price": 12.95
},
{
"id": "137",
"name": "Product #2",
"price": 82.95
}
]
}
答案 0 :(得分:1)
我认为BWJSONMatcher能够以非常简洁的方式帮助你:
ProductModel *productModel1 = [[ProductModel alloc] init];
productModel1.id = 123;
productModel1.name = @"Product #1";
productModel1.price = 12.95;
ProductModel *productModel2 = [[ProductModel alloc] init];
productModel2.id = 137;
productModel2.name = @"Product #2";
productModel2.price = 82.95;
OrderModel *orderModel = [[OrderModel alloc] init];
orderModel.order_id = 104;
orderModel.total_price = 103.45;
orderModel.products = @[productModel1, productModel2];
NSString *producedJSON = [orderModel toJSONString];