Create JSON Object from Class in Swift

andyopayne picture andyopayne · Jan 28, 2015 · Viewed 11.9k times · Source

I'm pretty new to iOS development and Swift (so please bear with me). I have a class object defined like this:

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

In my delegate, I create an instance of the class and append it to an array (declared outside the delegate):

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

So far so good. I can show the array values in a textview object in my viewcontroller and it is definitely adding values each time it updates.

Now, what I'd like to do is after the array count reaches a limit (say 100 values) then package it up as a JSON object and send it to a webserver using a HTPP Request. My initial thoughts were to use SwiftyJSON and Alamofire to help with this...but if I try to break the problem down into smaller parts then I need to:

  1. Create JSON object from array of LocationPoints
  2. Create HTTP request to send JSON packet to a webserver

Right now, I'm just trying to solve step 1, but can't seem to get started. I've used CocoaPods to install both pods (SwiftyJSON and Alamofire) but I don't know how to actually use them in my viewcontroller.swift file. Can anyone provide some guidance on how to create a JSON object from a custom class structure?

Answer

Marius Fanu picture Marius Fanu · Jan 28, 2015

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

}