andreich
andreich

Reputation: 1250

Swift. Mapping from JSON to object model. Array of Array

There's model in JSON format

{
    "offline": false,
    "data": {
        "path": [
            [ {
                    "Latitude": 56.789351316653,
                    "Longitude": 60.6053340947616
                }, {
                    "Latitude": 56.78674,
                    "Longitude": 60.60613
                }
            ], [ {
                    "Latitude": 56.79071,
                    "Longitude": 60.60492
                }, {
                    "Latitude": 56.79129,
                    "Longitude": 60.60493
                } ]
        ] } }    

and object model on swift

http://pastebin.com/j0mK8eYG

Issue: can't parse the path field of json, because there is an array of arrays. In the case of arrays with single dimension all works well.

Upvotes: 0

Views: 2067

Answers (3)

KP_G
KP_G

Reputation: 470

If you want to use a third party : There is this awesome and cleanly implemented open source objectMapper, works with Alamofire as well. Create models implementing protocol "Mappable" and custom arrays will be handled according to the Class specified. Reduces boiler plate code like anything.

If you want to parse it on your own : Simply create a helper method in your mdoel class to parse it using for loop.

init (responseDict: [String: Any]) {
    var itemModels : [ItemClass] = []
    let itemDictArray = responseDict["items"] as! [[String:Any]]

    for itemDict in itemDictArray {
        itemModels.append(ItemClass.init(dict: (itemDict as [String:Any]) ))
    }
}

Upvotes: 0

Syed Absar
Syed Absar

Reputation: 2284

1 - Generate the Swift models by copying the same Json at http://www.json4swift.com

2 - Copy the generated files to your project

3 - Open Data.swift, replace the following method

required public init?(dictionary: NSDictionary) {
if (dictionary["path"] != nil) { path = Path.modelsFromDictionaryArray(dictionary["path"] as! NSArray) }
}

to

required public init?(dictionary: NSDictionary) {
if let paths = dictionary["path"] as? NSArray {

    let allPaths = NSMutableArray()
    for patharr in paths {
        allPaths.addObjectsFromArray(Path.modelsFromDictionaryArray(patharr as! NSArray))
    }

}
}

4 - Success!

Upvotes: 0

eg.rudolph
eg.rudolph

Reputation: 311

I had to do something similar. I looked at the implementation of mtl_JSONArrayTransformerWithModelClass which transforms an array of dictionaries to and from an array of MTLModels. So I made a similar transformer which expects an array of array of dictionaries/MTLModels. I iterate over the outermost array and transform each array of dictionaries with the mtl_JSONArrayTransformerWithModelClass.

+ (NSValueTransformer *)JSONArrayOfArraysTransformerWithModelClass:(Class)modelClass

NSValueTransformer *arrayTransformer = [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:modelClass];

return [MTLValueTransformer
      reversibleTransformerWithForwardBlock:^id(NSArray *arrays) {
        if (arrays == nil) return nil;

        NSAssert([arrays isKindOfClass:NSArray.class], @"Expected an array, got: %@", arrays);

        NSMutableArray *modelArrays = [NSMutableArray arrayWithCapacity:[arrays count]];
        for (id JSONArray in arrays) {
          if (JSONArray == NSNull.null) {
            [modelArrays addObject:JSONArray];
            continue;
          }

          NSAssert([JSONArray isKindOfClass:NSArray.class], @"Expected an array of arrays of dictionaries, got array of: %@", JSONArray);

          NSArray *modelArray = [arrayTransformer transformedValue:JSONArray];
          if (modelArray == nil) continue;

          [modelArrays addObject:modelArray];
        }

        return modelArrays;
      }
      reverseBlock:^id(NSArray *arrays) {
        if (arrays == nil) return nil;

        NSAssert([arrays isKindOfClass:NSArray.class], @"Expected an array of arrays of MTLModels, got: %@", arrays);

        NSMutableArray *modelArrays = [NSMutableArray arrayWithCapacity:modelArrays.count];
        for (id modelArray in arrays) {
          if (modelArray == NSNull.null) {
            [modelArrays addObject:NSNull.null];
            continue;
          }

          NSAssert([modelArray isKindOfClass:NSArray.class], @"Expected an array of arrays, got array of: %@", modelArray);

          NSArray *array = [arrayTransformer reverseTransformedValue:modelArray];
          if (array == nil) continue;

          [modelArrays addObject:array];
        }

        return modelArrays;
      }];

}

Upvotes: 1

Related Questions