如何使用Swift格式化这些数据,以便后端可以读取它?

时间:2018-04-20 17:30:50

标签: ios json swift

我正在尝试格式化我的数据,以便我的后端可以读取它,但我觉得我错过了一些超级简单的东西。

以下是数据的外观:

{
    "month": 12,
    "year": 2012,
    "status": "Submitted",
    "expenses": [
        {
            "name": "MORTGAGE"
        },
        {
            "name": "HOTEL"
        }
    ]
}

根据我目前正在尝试从当前Stack Overflow问题和其他资源中解决的问题,这里是我目前得到的输出(格式化为便于阅读):

[
  "year": 2018,
  "status": "Not Submitted",
  "month": 3,
  "expenses": [
    ["name": "MORTGAGE"],
    ["name": "HOTEL"]
  ]
]

我有一个存储数据的数据对象,然后将所有值转换为[String:Any]。

var expenseObject = DocumentData_UploadData()
expenseObject.month = month
expenseObject.year = year
expenseObject.expenses = expenses
expenseObject.status = "Not Submitted"

let parameters = expenseObject.convertToDictionary()
print(parameters)

Alamofire.request(APIEndPoints.document_Create, method: .post, parameters: parameters, headers: headers).responseJSON

这是数据结构:

struct DocumentData_UploadData {

    var month = 0
    var year = 0
    var status = ""
    var expenses: [String] = []

    func convertToDictionary() -> [String: Any] {
        var expenseDict: [[String:Any]] = []
        for expense in expenses {
            expenseDict.append(["name":expense])
        }
        let dict: [String:Any] = [
            "month": month,
            "year": year,
            "status": status,
            "expenses": expenseDict
        ]
        return dict
    }

}

服务器可以成功读取我正在发送的数据中的月,年和状态值,但是无法读取费用值,这就是我挂断的地方。我尝试了几种不同的方法,但似乎总是得到服务器的相同拒绝,抱怨费用数据的格式。谢谢!

1 个答案:

答案 0 :(得分:1)

确实非常简单:我需要返回参数的标准[String:Any]格式,然后将JSONEncoding.default添加到Alamofire请求的编码值。我最终根本不需要DocumentData_UploadData类。

这是我的最终代码:

static func document_Create(month: Int, year: Int, expenses: [String], completion: @escaping (APIResponses, String?, DocumentData?) -> Void) {
    let headers = [
        "Authorization":getBearerAuthorization()
    ]

    let expensesDictionary: [[String:Any]] = expenses.map({ ["name": $0] })

    let parameters = [
        "month": month,
        "year": year,
        "status": "Not Submitted",
        "expenses": expensesDictionary
    ] as [String : Any]

    Alamofire.request(APIEndPoints.document_Create, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
        response in

        // Handle response
    }
}