Create JSON Object from Class in Swift

微笑、不失礼 提交于 2019-12-04 11:39:55

You should look over [NSJSONSerialization] class here.

class LocationPoint {
    var x: Double
    var y: Double
    var orientation: Double

    init(x: Double, y: Double, orientation: Double) {
        self.x = x
        self.y = y
        self.orientation = orientation
    }
}

func locationPointToDictionary(locationPoint: LocationPoint) -> [String: NSNumber] {
    return [
        "x": NSNumber(double: locationPoint.x),
        "y": NSNumber(double: locationPoint.y),
        "orientation": NSNumber(double: locationPoint.orientation)
    ]
}

var locationPoint = LocationPoint(x: 0.0, y: 0.0, orientation: 1.0)
var dictPoint = locationPointToDictionary(locationPoint)

if NSJSONSerialization.isValidJSONObject(dictPoint) {
    print("dictPoint is valid JSON")

    // Do your Alamofire requests

}

To add to Marius' answer, I modified the code a bit to convert a collection of Location Points into a valid JSON object. The answer above works for a single point, but this function can be used to convert an array of points.

func locationPointsToDictionary(locationPoints: [LocationPoint]) -> [Dictionary<String, AnyObject>] {
    var dictPoints: [Dictionary<String, AnyObject>] = []
    for point in locationPoints{
        var dictPoint = [
            "x": NSNumber(double: point.x),
            "y": NSNumber(double: point.y),
            "orientation": NSNumber(double: point.orientation),
            "timestamp": NSString(string: point.timestamp)
        ]
        dictPoints.append(dictPoint)
    }
    return dictPoints
}

Then, in the code you can use it like this:

var pt = LocationPoint(x: position.x, y: position.y, orientation: position.orientation, timestamp: timeStamp)
self.LocationPoints.append(pt)

if LocationPoints.count == 100 {
    var dictPoints = locationPointsToDictionary(self.LocationPoints)
    if NSJSONSerialization.isValidJSONObject(dictPoints) {
        println("dictPoint is valid JSON")

         // Do your Alamofire requests
    }
    //clear array of Location Points and start over
    LocationPoints = []
}

This should only package up the JSON object after there are 100 location points recorded. Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!