【发布时间】:2021-02-27 01:31:13
【问题描述】:
您好,我是初学者,正在尝试了解如何发送包含对象的数组。服务器是否了解数组是什么样的 Int、Strings 或 Booleans?您是否必须以 JSON 字符串的形式发送数组?什么我不明白?
var productsResult = ""
let encoder = JSONEncoder()
let productObject = ProductUsed(name: "Custom name", reason: "This Reason", apply_way: "Intravenous infusion", dosing: "2x", date_start: "22-02-1999", date_end: "22-03-2003")
do {
let result = try encoder.encode([productObject])
if let resultString = String(data: result, encoding: .utf8) {
print(resultString)
productsResult = resultString
}
} catch {
print(error)
}
json["products_used"] = productsResult
然后我用这样的参数发送到服务器:
parameters: ["pregnancy_week": 0, "body_height": 198, "initials": "John Appleseed", "heavy_effect": false, "sex": "Male", "pregnancy": false, "month_of_birth": 3, "reaction": "No option checked", "additional_info": "Eeee", "products_used": "[{\"date_end\":\"22-03-2003\",\"dosing\":\"2x\",\"date_start\":\"22-02-1999\",\"apply_way\":\"Intravenous infusion\",\"name\":\"Custom name\",\"reason\":\"This Reason\"}]", "description": "Eeee", "result": "Recovery without lasting consequences", "year_of_birth": 1983, "day_of_birth": 11, "issue_date": "15-11-2020", "body_weight": 78]
但是在日志中打印了“resultString”并且看起来不错...
[{"date_end":"22-03-2003","dosing":"2x","date_start":"22-02-1999","apply_way":"Intravenous infusion","name":"Custom name","reason":"This Reason"}]
我的代码有什么问题以及为什么“products_used”键中的单词之间有“\”?
【问题讨论】:
-
因为你做了
json["products_used"] = productsResult,所以你设置了一个字符串,所以你得到的是字符串化的JSON。json也不能是 Codable 吗? -
@Larme 你是对的。如何将值传递给此参数?
-
你为什么没有
struct SomenameThatMakeSense { let pregnancyWeek: Int; bodyHeight: Int; initials: String; ... let productsUsed = [ProductUsed]; ...}? -
@Larme 我有 struct,我就像那里一样:link
-
@Larme 当我从没有 JSONEncoder() 的 Api 方法中发送带有对象的数组时,参数看起来像:
"products_used": [testApp.ProductUsed(name: "Example", reason: "Some Test", apply_way: "Hmm Test", dosing: "Testable", date_start: "22-02-1998", date_end: "27-12-2010")],
标签: ios arrays json swift jsonencoder