varun aaruru varun aaruru - 2 months ago 5
Swift Question

How to frame following complex structure using dictionaries?

I need to pass data with following structure to web service.

required structure is :

{
"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"
}
]
}


I have separate dictionaries for
class
,
classLeader
and
classTeachers
dictionaries like this:

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


and

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


and two strings of
name
and
fathername


I tried to do with
[string:AnyObject]
and passing my dictionaries as anyobject but I am not able to succeed..the output I am getting is

{
"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"
]
]
}


I am not getting any idea how to frame the required structure.Help me in this issue.

Answer

You might need to JsonSerialize the data. Try this.

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)