使用Mantle将JSON数组中的NSString转换为NSURL [英] Transform NSString to NSURL within a JSON Array with Mantle
问题描述
让我说的是以下JSON响应
Let's say given to me is the following JSON response
{
"images": [
"http://domain.com/image1.jpg",
"http://domain.com/image2.jpg",
"http://domain.com/image3.jpg"
]
}
我想使用Mantle解析这些字符串并将其转换为NSURL,但将其保留在NSArray中.
With Mantle I want to parse those strings and transform them into NSURLs but keep them in an NSArray.
所以我的Objective-C模型对象看起来像
So my Objective-C model object would look like
@interface MyModel : MTLModel <MTLJSONSerializing>
// Contains NSURLs, no NSStrings
@property (nonatomic, copy, readonly) NSArray *images;
@end
是否有一种优雅的方法来实现这一目标?一些NSURL数组转换器?
Is there an elegant way to achieve that? Some NSURL array transformer?
+ (NSValueTransformer*)imagesJSONTransformer
{
return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[NSURL class]];
}
很显然,NSURL不是从MTLModel派生的,所以这是行不通的.
Obviously NSURL does not derive from MTLModel, so that will not work.
推荐答案
不幸的是,Mantle 1.x没有简单的方法将现有的转换器(在本例中为名为MTLURLValueTransformerName的转换器)应用到数组.
Unfortunately, Mantle 1.x doesn't have an easy way to apply an existing transformer (in this case, the transformer named MTLURLValueTransformerName) to each element of an array.
您可以这样做:
+ (NSValueTransformer*)imagesJSONTransformer {
NSValueTransformer *transformer = [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
return [MTLValueTransformer transformerWithBlock: ^NSArray *(NSArray *values) {
NSMutableArray *transformedValues = [NSMutableArray arrayWithCapacity:values.count];
for (NSString *value in values) {
id transformedValue = [transformer transformedValue:value];
if (transformedValue) {
[transformedValues addObject:transformedValue];
}
}
return transformedValues;
}];
}
在Mantle 2.0中,您将可以使用预定义的数组映射转换器. Mantle 2.0仍在开发中.
In Mantle 2.0, you'll be able to use the predefined array mapping transformer. Mantle 2.0 is still in development.
这篇关于使用Mantle将JSON数组中的NSString转换为NSURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!