在Swift中从类创建JSON对象 [英] Create JSON Object from Class in Swift

查看:269
本文介绍了在Swift中从类创建JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对iOS开发和Swift非常陌生(请耐心等待)。我有一个这样定义的类对象:

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)

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

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.

现在,我想做的是数组计数达到限制(例如100个值),然后将其打包为JSON对象,并使用HTPP请求将其发送到Web服务器。我最初的想法是使用 SwiftyJSON Alamofire 可以帮助解决此问题...但是,如果我尝试将问题分解为更小的部分,则需要:

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. 从LocationPoints数组创建JSON对象

  2. 创建HTTP请求以将JSON数据包发送到网络服务器

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

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?

推荐答案

您应该查看 [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

}

这篇关于在Swift中从类创建JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆