Swift:将字典转换为 JSON for multipart/Form-Data
Swift: Convert Dictionary into JSON for multipart/Form-Data
我有一个 swift 应用程序,它向服务器发出具有正常值和图像的请求,所以我使用 multipart/form-data 请求。我有一个包含我所有值的对象,如下所示:
struct parameters: Codable {
var request : String = "blah"
var arrayData : [String] = ["bleh", "bluh"]
var dictionaryData : [String: String] = ["1": "Blah", "2": "Blah"]
}
但是,我无法将数组和字典的 json 转换版本插入到 httpBody 中。
我试过使用 JSONEncoder(),但它会将整个对象转换为 JSON,而且我无法插入边界和其他内容。有什么方法可以将数组和字典转换为 json 格式,然后我可以将其作为值插入 multipart/form-data 请求中。
例如,对于字符串、字典和数组,它将 return
"blah"
["bleh", "bluh"]
{"1": "Blah", "2": "Blah"}
let dictParam = NSMutableDictionary() //字典
var ids = [String]()
let cat = (Constants.app_delegate.dictAddPostInfo.object(forKey: "categoryArr") as! NSArray)
//filter id from dic and add in ids
for dic in cat {
let dic = dic as! NSDictionary
let id = dic["id"] as! Int
ids.append(String(id))
}
//set data to dicParam
for i in 0..<ids.count {
let key = String.init(format: "categories[%d]", i)
dictParam.setValue(ids[i], forKey: key)
}
//For single value
dictParam.setValue(Constants.app_delegate.dictAddPostInfo.object(forKey: "Title") as! String, forKey: "title")
dictParam.setValue(Constants.app_delegate.dictAddPostInfo.object(forKey: "Description") as! String, forKey: "description")
dictParam.setValue(Constants.app_delegate.dictAddPostInfo.object(forKey: "Price") as! String, forKey: "price")
dictParam.setValue(latitude, forKey: "latitude")
dictParam.setValue(longitude, forKey: "longitude")
if let area = Constants.app_delegate.dictAddPostInfo.object(forKey: "area") as? String {
dictParam.setValue(area, forKey: "area")
}
else {
dictParam.setValue("", forKey: "area")
}
if let city = Constants.app_delegate.dictAddPostInfo.object(forKey: "city") as? String {
dictParam.setValue(city, forKey: "city")
}
else {
dictParam.setValue("", forKey: "city")
}
if let state = Constants.app_delegate.dictAddPostInfo.object(forKey: "state") as? String {
dictParam.setValue(state, forKey: "state")
}
else {
dictParam.setValue("", forKey: "state")
}
if let zip = Constants.app_delegate.dictAddPostInfo.object(forKey: "zip") as? String {
dictParam.setValue(zip, forKey: "zip")
}
else {
dictParam.setValue("", forKey: "zip")
}
这里是字典转换成json
的代码
if let jsonData = try? JSONSerialization.data(withJSONObject: dictParam, options: .prettyPrinted), let theJSONText = String(data: jsonData, encoding: .ascii) {
print(theJSONText)
}
您可以只对单独的组件进行编码,而不是对整个结构进行编码。使用上面的例子:
let paramters = Parameters()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let request = try! encoder.encode(paramters.request)
let array = try! encoder.encode(paramters.arrayData)
let dict = try! encoder.encode(paramters.dictionaryData)
这将单独为您提供组件,然后您可以访问它们并根据需要使用它们。作为一个简单的例子:
print("Request \n", String(data: request, encoding: .utf8)!, "\n\n")
print("Array \n", String(data: array,encoding: .utf8)!, "\n\n")
print("Dict \n", String(data: dict ,encoding: .utf8)!, "\n\n")
正在输出...
Request
"blah"
Array
[ "bleh", "bluh" ]
Dict
{ "2" : "Blah", "1" : "Blah" }
我有一个 swift 应用程序,它向服务器发出具有正常值和图像的请求,所以我使用 multipart/form-data 请求。我有一个包含我所有值的对象,如下所示:
struct parameters: Codable {
var request : String = "blah"
var arrayData : [String] = ["bleh", "bluh"]
var dictionaryData : [String: String] = ["1": "Blah", "2": "Blah"]
}
但是,我无法将数组和字典的 json 转换版本插入到 httpBody 中。 我试过使用 JSONEncoder(),但它会将整个对象转换为 JSON,而且我无法插入边界和其他内容。有什么方法可以将数组和字典转换为 json 格式,然后我可以将其作为值插入 multipart/form-data 请求中。
例如,对于字符串、字典和数组,它将 return
"blah"
["bleh", "bluh"]
{"1": "Blah", "2": "Blah"}
let dictParam = NSMutableDictionary() //字典
var ids = [String]()
let cat = (Constants.app_delegate.dictAddPostInfo.object(forKey: "categoryArr") as! NSArray)
//filter id from dic and add in ids
for dic in cat {
let dic = dic as! NSDictionary
let id = dic["id"] as! Int
ids.append(String(id))
}
//set data to dicParam
for i in 0..<ids.count {
let key = String.init(format: "categories[%d]", i)
dictParam.setValue(ids[i], forKey: key)
}
//For single value
dictParam.setValue(Constants.app_delegate.dictAddPostInfo.object(forKey: "Title") as! String, forKey: "title")
dictParam.setValue(Constants.app_delegate.dictAddPostInfo.object(forKey: "Description") as! String, forKey: "description")
dictParam.setValue(Constants.app_delegate.dictAddPostInfo.object(forKey: "Price") as! String, forKey: "price")
dictParam.setValue(latitude, forKey: "latitude")
dictParam.setValue(longitude, forKey: "longitude")
if let area = Constants.app_delegate.dictAddPostInfo.object(forKey: "area") as? String {
dictParam.setValue(area, forKey: "area")
}
else {
dictParam.setValue("", forKey: "area")
}
if let city = Constants.app_delegate.dictAddPostInfo.object(forKey: "city") as? String {
dictParam.setValue(city, forKey: "city")
}
else {
dictParam.setValue("", forKey: "city")
}
if let state = Constants.app_delegate.dictAddPostInfo.object(forKey: "state") as? String {
dictParam.setValue(state, forKey: "state")
}
else {
dictParam.setValue("", forKey: "state")
}
if let zip = Constants.app_delegate.dictAddPostInfo.object(forKey: "zip") as? String {
dictParam.setValue(zip, forKey: "zip")
}
else {
dictParam.setValue("", forKey: "zip")
}
这里是字典转换成json
的代码 if let jsonData = try? JSONSerialization.data(withJSONObject: dictParam, options: .prettyPrinted), let theJSONText = String(data: jsonData, encoding: .ascii) {
print(theJSONText)
}
您可以只对单独的组件进行编码,而不是对整个结构进行编码。使用上面的例子:
let paramters = Parameters()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let request = try! encoder.encode(paramters.request)
let array = try! encoder.encode(paramters.arrayData)
let dict = try! encoder.encode(paramters.dictionaryData)
这将单独为您提供组件,然后您可以访问它们并根据需要使用它们。作为一个简单的例子:
print("Request \n", String(data: request, encoding: .utf8)!, "\n\n")
print("Array \n", String(data: array,encoding: .utf8)!, "\n\n")
print("Dict \n", String(data: dict ,encoding: .utf8)!, "\n\n")
正在输出...
Request
"blah"
Array
[ "bleh", "bluh" ]
Dict
{ "2" : "Blah", "1" : "Blah" }