在Swift中从Class创建JSON对象

and*_*yne 3 swift alamofire swifty-json

我对iOS开发和Swift很新(所以请耐心等待).我有一个像这样定义的类对象:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的委托中,我创建了一个类的实例并将其附加到一个数组(在委托之外声明):

var pt = LocationPoint(x: position.x, y: position.y, orientation: position.orientation)
self.LocationPoints.append(pt)
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.我可以在viewcontroller中的textview对象中显示数组值,并且每次更新时肯定会添加值.

现在,我想要做的是在数组计数达到限制(比如说100个值)之后,然后将其打包为JSON对象,并使用HTPP请求将其发送到Web服务器.我最初的想法是使用SwiftyJSONAlamofire来帮助解决这个问题......但如果我试图将问题分解成更小的部分,那么我需要:

  1. 从LocationPoints数组创建JSON对象
  2. 创建HTTP请求以将JSON数据包发送到Web服务器

现在,我只是想解决第1步,但似乎无法开始.我已经使用CocoaPods安装了两个pod(SwiftyJSON和Alamofire),但我不知道如何在我的viewcontroller.swift文件中实际使用它们.任何人都可以提供有关如何从自定义类结构创建JSON对象的一些指导?

Mar*_*anu 7

你应该在这里看一[NSJSONSerialization]下课.

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

}
Run Code Online (Sandbox Code Playgroud)