How to use an NSArray not key-value pair with Mantle

137 Views Asked by At

If I have a JSON array like this,

{
  "list": [
    "javascript", 
    "stockFields",
    "stockLists"
  ]
}

and two models like:

@interface stockList : MTLModel <MTLJSONSerializing>

@property(nonatomic, copy, readonly) NSArray *stockListItems;

@end

@interface stockListItem : MTLModel

@property(nonatomic, copy, readonly) NSString *javascript;

@property(nonatomic, copy, readonly) NSString *stockFields;

@property(nonatomic, copy, readonly) NSString *stockLists;

@end

stockList.m

+ (NSDictionary*)JSONKeyPathsByPropertyKey {
    return @{
             @"stockListItems":@"list",
             };
}

+ (NSValueTransformer *)stockLstItemsJSONTransformer {



}

How to parse JSON list array attribute storage stockListItem's properyty ?thanks a lot!

2

There are 2 best solutions below

0
On

You just set them by index if you are sure the indexes are:

    javascript = stockListItems[0];
    stockFields = stockListItems[1];
    stockLists = stockListItems[2];

Otherwise, you could have another Dictionary in list to get exact data you want, just like:

{
  "list": [
    item1: "javascript", 
    item2: "stockFields",
    item3: "stockLists"
  ]
}

and now:

javascript = [list objectForKey:@"item1"];
stockFields = [list objectForKey:@"item2"];
stockLists = [list objectForKey:@"item3"];

Hope this could help.

1
On

You can parse JSON with NSJSONSerialization's class method JSONObjectWithData.

It'll return a NSDictionary and then you can access the "list" field like so:

NSMutableDictionary *parsedJSON = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: nil];
stockListObj.stockListItems = parsedJSON[@"list"];