【问题标题】:How to frame following complex structure using dictionaries?如何使用字典构建以下复杂结构?
【发布时间】:2017-02-14 17:54:51
【问题描述】:

我需要将具有以下结构的数据传递给 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"
      }
   ]
}

我有单独的字典用于 class 、 classLeader 和 classTeachers 字典,如下所示:

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]

还有两串name和fathername

我尝试使用 [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"
      ]
   ]
}

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

【问题讨论】:

  • 你遇到什么错误?
  • 请检查两个 jsons .... 我正在 [ 代替 { .. 那是错误
  • 如果您创建 swift 通用字典,这不是错误控制台正在使用 [ 显示字典。
  • 您在将其发送到服务器时遇到过问题吗? @NiravD 是对的。
  • 是的,这不是错误,但是在发送到服务器时,我收到了错误

标签: ios swift dictionary nsdictionary


【解决方案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)

【讨论】:

  • 但在转换为 json 时..我没有得到双引号
  • 编辑反映相同
猜你喜欢
  • 2011-10-20
  • 2011-12-07
  • 2015-11-08
  • 2017-04-06
  • 2017-05-09
  • 2011-10-06
  • 2014-05-07
  • 2018-05-18
  • 1970-01-01
相关资源
最近更新 更多