0

When parsing valid GeoJSON data containing escaped double-quotes, the MKGeoJSONDecoder fails with error.

Steps to reproduce:

Run the following code block in a .swift playground

import Foundation
import MapKit

//Valid data verifed using http://geojson.io  
if let data = """  
        {  
            "features": [  
                {  
                    "geometry": {  
                        "coordinates": [  
                            13.38678,  
                            52.52548  
                        ],  
                        "type": "Point"  
                    },  
                    "properties": {  
                        "description": " \" text in double quotes \" ",  
                        "href": "/sen/web/service/liefer-und-abholdienste/index.php/detail/1848",  
                        "id": "/sen/web/service/liefer-und-abholdienste/index.php/detail/1848",  
                        "title": "1848"  
                    },  
                    "type": "Feature"  
                }  
            ],  
            "type": "FeatureCollection"  
        }  
    """.data(using: .utf8) {  
    let decoder = MKGeoJSONDecoder()  
    do {  
        let decoded = try decoder.decode(data)  
        if let firstFeature = decoded.first as? MKGeoJSONFeature,  
            let firstCoordinate = firstFeature.geometry.first?.coordinate {  
            print("Latitude: \(firstCoordinate.latitude) Longitude : \(firstCoordinate.longitude)")  
        }  

    } catch (let error) {  
        print(error)  
    }  
}  

The catch block will report an error saying: “The data couldn’t be read because it isn’t in the correct format.”

If we change the “description” string and remove the escaped double-quotes “\, the MKGeoJSONDecoder decodes the data without issue.

Edit: After removing localisedDescription, the error shown is:

Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around character 325." UserInfo={NSDebugDescription=Badly formed object around character 325.}

Sam Khawase
  • 348
  • 6
  • 21
  • 1
    Never `print(error.localizedDescription)`, always do `print(error)`. It tells you exactly what's wrong and where. – vadian Apr 20 '20 at 14:38
  • @vadian: I've updated the error, but I'm still lost what could be wrong with that character. – Sam Khawase Apr 20 '20 at 19:26
  • Possibly helpful: https://stackoverflow.com/a/47388413 . This is a strange problem: I was able to get it to parse when changing description to `" \\" text in double quotes \\" "`. Clearly not ideal as that change is not valid GeoJSON. Tested with geojsonlint.com – RobLabs May 11 '20 at 20:33

0 Answers0