Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform NSString to NSURL within a JSON Array with Mantle

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"
    ]
}

With Mantle I want to parse those strings and transform them into NSURLs but keep them in an NSArray.

So my Objective-C model object would look like

@interface MyModel : MTLModel <MTLJSONSerializing>
// Contains NSURLs, no NSStrings
@property (nonatomic, copy, readonly) NSArray *images;
@end

Is there an elegant way to achieve that? Some NSURL array transformer?

+ (NSValueTransformer*)imagesJSONTransformer
{
    return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[NSURL class]];
}

Obviously NSURL does not derive from MTLModel, so that will not work.

like image 818
Martin Stolz Avatar asked Mar 14 '26 21:03

Martin Stolz


1 Answers

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.

You can do it like this:

+ (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;
    }];
}

In Mantle 2.0, you'll be able to use the predefined array mapping transformer. Mantle 2.0 is still in development.

like image 141
David Snabel-Caunt Avatar answered Mar 17 '26 19:03

David Snabel-Caunt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!