且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为POST请求将对象转换为JSON字符串

更新时间:2023-01-23 19:08:45

你需要通过添加如下函数将两个对象转换为字典:

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.