1

Lets say I have this Model.

@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

Questions:

  1. How I can add products in this array?
  2. Then how I can produce the following JSON.

    "products" : [ { "id": "123", "name": "Product #1", "price": 12.95 }, { "id": "137", "name": "Product #2", "price": 82.95 } ]

or the whole object.

{
  "order_id": 104,
  "total_price": 103.45,
  "products" : [
    {
      "id": "123",
      "name": "Product #1",
      "price": 12.95
    },
    {
      "id": "137",
      "name": "Product #2",
      "price": 82.95
    }
  ]
}
itsaboutcode
  • 24,525
  • 45
  • 110
  • 156

1 Answers1

1

I think BWJSONMatcher can help you out in a extremely neat way:

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];
Burrows Wang
  • 249
  • 1
  • 7