我正在尝试使用 Swift 构建以下 JSON,因为这在我使用 Postman 进行测试时有效。我需要能够更改参数的值,所以我试图避免只构建一个字符串:
{
"item": {
"record": "10",
"field_name": "orientation_forward",
"redcap_repeat_instance": "1",
"redcap_repeat_instrument": "range_of_motion_result",
"value": "4",
"redcap_event_name": []
}
}
这是我这样做的尝试,但当我测试它时,它甚至似乎不是有效的 JSON:
var record = "10"
var field_name = "orientation_forward"
var repeat_instance = "1"
var repeat_instrument = "range_of_motion_result"
var value = "4"
var event: [String] = [] // not sure how else to pass in '[]' when empty
let dataObject: [String: Any] = [
"item":
["record": record,
"field_name": field_name,
"redcap_repeat_instance": repeat_instance,
"redcap_repeat_instrument": repeat_instrument,
"value": value,
"redcap_event_name": event]
]
if let jsonData = try? JSONSerialization.data(withJSONObject: dataObject, options: .init(rawValue: 0)) as? Data
{
// Check if it worked...
print(String(data: jsonData!, encoding: .utf8)!)
let jsonTest = JSONSerialization.isValidJSONObject(jsonData) // false!
print(jsonTest)
}
所有的帮助都亲切地接受了。提前致谢。