1

This is my class:

public class Coordinate: NSObject{
public var lat: Double
public var lon: Double

init(latitude: Double, longitude: Double) {
    self.lat = latitude
    self.lon = longitude
}

init(coder aDecoder: NSCoder!) {
    self.lat = aDecoder.decodeObjectForKey("latitude") as! Double
    self.lon = aDecoder.decodeObjectForKey("longitude") as! Double
}

func encodeWithCoder(aCoder: NSCoder!) {
    aCoder.encodeObject(lat, forKey: "latitude")
    aCoder.encodeObject(lon, forKey: "longitude")
}

and thats the way I would get an string of my Array of Object:

var endlist = [Coordinate]()

let data = try NSJSONSerialization.dataWithJSONObject(endlist , options: options)           
let string = NSString(data: data, encoding: NSUTF8StringEncoding)          
json["points"] = string

And now I get this Error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Test.Coordinate)'

Can someone please help me with this problem?

So in json["points"] must be this:

"points": [
{"lat": 47424212, "lon": 8855883},
{"lat": $lat2, "lon": $lon2}
]

THANKS!

1 Answer 1

2

You cannot encode your Coordinate class that way using NSCoding. One thing you can do is create some method to convert it to some JSON object and then convert it to json string. Then you could use a simple struct instead of a class of type NSObject.

public struct Coordinate {
    public var lat: Double
    public var lon: Double

    func toJSONDict() -> [String: String] {
        return [
            "lat": String(lat),
            "lon": String(lon)
        ]
    }
}



var endlist = [Coordinate]()

endlist.append(Coordinate(lat: 47424212, lon: 8855883))

let jsonDict = endlist.map{ $0.toJSONDict() }

print(jsonDict)

if let jsonData = try? NSJSONSerialization.dataWithJSONObject(jsonDict, options: .PrettyPrinted) {
    if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
        print(jsonString)
    }
}
Sign up to request clarification or add additional context in comments.

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.