如何使用字典框架复杂的结构?

时间:2016-10-06 05:43:02

标签: ios swift dictionary nsdictionary

我需要将具有以下结构的数据传递给Web服务。

所需的结构是:

{  
   "Name":"abc",
   "fatherName":"xyz",
   "class":{  
      "id":"1",
      "className":"MPC",
      "classDesc":"Maths,Physics,chemistry"
   },
   "classLeader":{  
      "id":"123",
      "firstName":"def",
      "lastName":"ghi",
      "emailId":"def.ghi@jkl.com"
   },
   "classTeachers":[  
      {  
         "id":"567894",
         "firstName":"xxx",
         "lastName":"V",
         "emailId":"xxx.V@jkl.com"
      }
   ]
}

我有classclassLeaderclassTeachers词典的单独词典,如下所示:

class = ["id":"1","className":"MPC","classDesc":"Maths,Physics,chemistry"]
classLeader = ["id":"123","firstName":"def","lastName":"ghi","emailId":"def.ghi@jkl.com"

classTeacher = ["id":"567894","firstName":"xxx","lastName":"v","emailId":"xxx.v@jkl.com]

以及两个namefathername

字符串

我尝试使用[string:AnyObject]并将我的词典作为任何对象传递,但我无法成功...我得到的输出是

{  
   "Name":"abc",
   "fatherName":"xyz",
   "class":[ 
      "id":"1",
      "className":"MPC",
      "classDesc":"Maths,Physics,chemistry"
   ],
   "classLeader":[  
      "id":"123",
      "firstName":"def",
      "lastName":"ghi",
      "emailId":"def.ghi@jkl.com"
   ],
   "classTeachers":[  
      [  
         "id":"567894",
         "firstName":"xxx",
         "lastName":"V",
         "emailId":"xxx.V@jkl.com"
      ]
   ]
}

我不知道如何构建所需的结构。在这个问题上帮助我。

1 个答案:

答案 0 :(得分:1)

您可能需要JsonSerialize数据。试试这个。

let clas = ["id":"1","className":"MPC","classDesc":"Maths,Physics,chemistry"]
let classLeader = ["id":"123","firstName":"def","lastName":"ghi","emailId":"def.ghi@jkl.com"]
let classTeacher = ["id":"567894","firstName":"xxx","lastName":"v","emailId":"xxx.v@jkl.com"]

let dict = ["name": "ABC", "fatherName": "XYZ", "class": clas, "classLeader": classLeader, "classTeachers": classTeacher]

let jsonData = try? NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
let jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)

print(jsonString)