0

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.

8
  • Why does the JSON contain an array of arrays? Commented Oct 10, 2014 at 17:03
  • @Wain because it is a server model Commented Oct 11, 2014 at 8:03
  • Logically, what do the nested arrays represent? Are there always 2 items in the inner arrays? Why isn't a similar structure used on the client (or is that actually your goal)? Commented Oct 11, 2014 at 9:40
  • @Wain, it's just example, I can't change structure Commented Oct 11, 2014 at 12:57
  • 1
    Look at creating a custom value transformer Commented Oct 11, 2014 at 17:45

3 Answers 3

1

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

}

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.