如何使用NSArray而不是Mantle的键值对

时间:2015-08-24 03:00:01

标签: objective-c github-mantle

如果我有这样的JSON数组,

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

和两个模型如:

@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 {



}

如何解析JSON列表数组属性存储stockListItem的优点?非常感谢!

2 个答案:

答案 0 :(得分:1)

如果你确定索引是:

,你只需按索引设置它们
    javascript = stockListItems[0];
    stockFields = stockListItems[1];
    stockLists = stockListItems[2];

否则,您可以在Dictionary中使用其他list来获取所需的确切数据,如:

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

现在:

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

希望这可以提供帮助。

答案 1 :(得分:0)

您可以使用NSJSONSerialization的类方法JSONObjectWithData解析JSON。

它会返回NSDictionary然后您可以像这样访问“list”字段:

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