如何在SwiftyJSON中使用数组解析和数组数组?

时间:2018-07-10 10:19:25

标签: ios json swift swifty-json

我有一个如下的JSON响应

{
        "geometry" : {
          "type" : "GeometryCollection",
          "geometries" : [
            {
              "type" : "Polygon",
              "coordinates" : [
                [
                  [
                    43.7228393554688,
                    42.065249641381598
                  ],
                  [
                    43.8217163085938,
                    42.084617318779898
                  ],
                  [
                    43.899993896484403,
                    42.100922357518499
                  ],
                  [
                    43.7228393554688,
                    42.065249641381598
                  ]
                ]
              ]
            }
          ]
        }

我上面发布的JSON是我的JSON响应的一部分。该数组以以下格式提供数据。

[[[Array_Polygon1_Coordinates1], [Array_Polygon1_Coordinates2],[Array_Polygon1_Coordinates3]], [[Array_Polygon2_Coordinates1], [Array_Polygon2_Coordinates2], [Array_Polygon2_Coordinates3]]]

我在我的项目中使用SwiftyJSON。如何使用SwiftyJSON解析此JSON? 我的代码

guard let geometries: Array = event["geometry"]["geometries"].array else {
                    throw RMException.invalidFormat
                }
                for geometry: JSON in geometries {
                    if let coordinatesArray: Array = geometry["coordinates"].array {
                        for coordinates: JSON in coordinatesArray {
                            var polygonCoordinates: [CLLocationCoordinate2D] = []
                            for coordinatePair in coordinates {
                                guard let coordinatePair = coordinatePair.array,
                                    let latitude: Double = coordinatePair.last?.double,
                                    let longitude: Double = coordinatePair.first?.double else {
                                        throw RMException.invalidFormat
                                }

                                polygonCoordinates.append(CLLocationCoordinate2DMake(latitude, longitude))
                            }
                        }
                    }
                }

我得到的错误是 enter image description here

1 个答案:

答案 0 :(得分:2)

正如Pratik在评论中提到的,我通过以下方式解决了问题

if let coordinatesArray: Array = geometry[RMJSONKey.coordinates].array {
   for coordinates: JSON  in coordinatesArray {
       var polygonCoordinates: [CLLocationCoordinate2D] = []
       for coordinatePair: (String, JSON) in coordinates {
           let coordinateSet: JSON = coordinatePair.1
           guard let latitude: Double = coordinateSet.arrayValue.last?.double,
           let longitude: Double = coordinateSet.arrayValue.first?.double else {
                throw RMException.invalidFormat
           }
          polygonCoordinates.append(CLLocationCoordinate2DMake(latitude, longitude))
       }
   }
}