简体   繁体   English

如何将 JSON 转换为 Swift Dictinary 以进行 HTTP POST

[英]How can I convert JSON to Swift Dictinary inorder to make an HTTP POST

I am having issues to successfully structure my json data into a swift dictionary inorder to send my HTTP body via an API我在将我的 json 数据成功构建到一个 swift 字典以便通过 API 发送我的 HTTP 正文时遇到问题

This is how my Json is structured:这是我的 Json 的结构:

{
  "idNo": "string",
  "name": "string",
  "isRegistered": true,
  "customMessage": "string",
  "riskStatus": "Low",
  "exposureBasedRiskStatus": "Low",
  "symptomBasedRiskStatus": "Low",
  "riskMessage": "string",
  "doYouHaveATemperature": true,
  "temperature": 0,
  "asessmentQuestion": [
    {
      "question": "string",
      "answer": "string",
      "createdBy": "string"
    },
    {
      "question": "string",
      "answer": "string",
      "createdBy": "string"
    },
    {
      "question": "string",
      "answer": "string",
      "createdBy": "string"
    },
    {
      "question": "string",
      "answer": "string",
      "createdBy": "string"
    },
    {
      "question": "string",
      "answer": "string",
      "createdBy": "string"
    }
  ]
}

the object "asessmentQuestion" is an array of different questions, can't seem to figure out how to convert this structure to a swift dictionary or another recommended format for me to be able to post my data.对象“评估问题”是一系列不同的问题,似乎无法弄清楚如何将此结构转换为快速字典或其他推荐格式以便我能够发布我的数据。 My API is always saying bad request and I'm pretty sure I am not correctly mapping the json data.我的 API 总是说错误的请求,我很确定我没有正确映射 json 数据。

this is a snippet of how I am attempting to map my json data:这是我如何尝试映射我的 json 数据的片段:

   var dictionary = [String:Any]()
    
    dictionary["1. How old are you?"] = model.riskExposureBasedAssessment[0].answer
    dictionary["2. Have you ever visited a COVID affected country?"] = model.riskExposureBasedAssessment[1].answer
    dictionary["3. do you frequently experience flu like symptoms?"] = model.riskExposureBasedAssessment[2].answer
    dictionary["4. Where you providing care in a non-health setting for a person with symptomatic COVID-19 infection"] = model.riskExposureBasedAssessment[3].answer
    dictionary["5. Did you come in close contact* with a person with symptomatic laboratory-confirmed COVID-19 infection?"] = model.riskExposureBasedAssessment[4].answer
    
    let parameters = [
        "idNo": model.id,
        "name": model.name,
        "isRegistered": model.isRegistered,
        "customMessage": model.customResponse,
        "riskStatus": model.riskStatus,
             "exposureBasedRiskStatus": model.exposureBasedRiskStatus,
             "symptomBasedRiskStatus": model.symptomBasedRiskStatus,
             "riskMessage": model.riskMessage,
             "doYouHaveATemperature": model.doYouHaveATemperature,
             "temperature": model.temperature,
        "exposureBasedAssessments":  dictionary
        
        ] as [String:Any]
    
    
    
    let postData = try? JSONSerialization.data(withJSONObject: parameters)

It's an array of dictionary, so :这是一个字典数组,所以:

var dictionaries: [[String: Any]] = []
// Populate dictionaries
// ...

let parameters = [
    "idNo": model.id,
    "name": model.name,
    "isRegistered": model.isRegistered,
    "customMessage": model.customResponse,
    "riskStatus": model.riskStatus,
    "exposureBasedRiskStatus": model.exposureBasedRiskStatus,
    "symptomBasedRiskStatus": model.symptomBasedRiskStatus,
    "riskMessage": model.riskMessage,
    "doYouHaveATemperature": model.doYouHaveATemperature,
    "temperature": model.temperature,
    "exposureBasedAssessments":  dictionaries    
    ] as [String:Any]

Then, to populate it:然后,填充它:

var dict1: [String: Any] = [:]
dict1["question"] = "1. How old are you?"
dict1["answer"] = model.riskExposureBasedAssessment[0].answer
dictionaries.append(dict1)

var dict2: [String: Any] = [:]
dict2["question"] = "2. Have you ever visited a COVID affected country?"
dict2["answer"] = model.riskExposureBasedAssessment[1].answer
dictionaries.append(dict2)

...

or或者

var dict1: [String: Any] = ["question": "1. How old are you?",
                            "answer": model.riskExposureBasedAssessment[0].answer]
dictionaries.append(dict1)

var dict2: [String: Any] = ["question": "2. Have you ever visited a COVID affected country?"",
                            "answer": model.riskExposureBasedAssessment[1].answer]
dictionaries.append(dict2)

...

But, I guess you have can retrieve the question from model.riskExposureBasedAssessment[n] , Instead of "1. How old are you?"但是,我想您可以从model.riskExposureBasedAssessment[n]检索问题,而不是"1. How old are you?" , can't you do model.riskExposureBasedAssessment[0].question ? ,你不能做model.riskExposureBasedAssessment[0].question吗?

If that's the case, you can use a for loop: so I'd go with:如果是这种情况,您可以使用 for 循环:所以我会选择:

for aQuestionModel in model.riskExposureBasedAssessment {
    let questionDict = ["question": aQuestionModel.question,
                        "answer": aQuestionModel.answer]
    dictionaries.append(questionDict)
}

Or, once you master basic algorithm, closures, and map() :或者,一旦您掌握了基本算法、闭包和map()

var dictionaries = model.riskExposureBasedAssessment.map { ["question": $0.question, "answer": $0.answer] }

It's missing the "createdBy", I don't know where to find it and if it's optional, but I think you should be able to add it if needed.它缺少“createdBy”,我不知道在哪里可以找到它以及它是否是可选的,但我认为您应该可以在需要时添加它。

NotaBene: Code not tested against a compiler. NotaBene:代码未针对编译器进行测试。 It should work, at maybe one or two typos.它应该可以工作,可能会有一两个错别字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM