为POST请求将对象转换为JSON字符串 [英] Converting Object to JSON String For POST Request
问题描述
我有一个对象,它是类似于这个类的实例:
I have an object that is an instance of a class similar to this:
class MyClass {
let aString: String
let bString: String
var cArray = [AnotherClass]()
init etc...
}
AnotherClass类似于:
AnotherClass is something like:
class AnotherClass {
let aInt: Int
let bInt: Int
var cFloat = Float
init etc...
}
好的,现在我需要将该对象(MyClass的实例)作为POST请求 string 参数传递使用以下格式:
Ok, now i need to pass that object (instance of MyClass) as a POST request string parameter with the following format:
{
"aString": "1",
"bString": "yannis",
"cArray": [
{
"aInt": 1965887,
"bInt": 36513032311523,
"cFloat": 1.0
},
{
"aInt": 1916915,
"bInt": 360397932121597,
"cFloat": 1.0
}
]
}
任何想法如何实现这一目标?我正在使用Swift 1.2(和SwiftyJSON,如果有帮助的话)
谢谢!
Any ideas how to achieve this? I'm using Swift 1.2 (and SwiftyJSON, if that helps) Thanks!
推荐答案
你需要通过添加如下函数将两个对象转换为字典:
You'll need to convert both objects into Dictionaries by adding a function like:
func convertToDictionary() -> Dictionary<String, AnyObject> {
return [
"aString": self.aString,
"bString": self.bString,
"cArray": self.cArray
]
}
。
然后使用以下方法对其进行序列化:
Then serialize it using:
let theJSONData = NSJSONSerialization.dataWithJSONObject(
dictionary ,
options: NSJSONWritingOptions(0),
error: nil)
其中字典
类似于 dictionary = myClass.convertToDictionary
在序列化 MyClass
对象之前,甚至可以序列化数组中的嵌套对象 MyClass
。
Maybe even serialize the nested objects in the Array for MyClass
before serializing the MyClass
object as well.
这篇关于为POST请求将对象转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!