[英]How to add a key value pair to a dictionary of type [String:AnyObject] in Swift?
[英]Swift Dictionary adding square brackets after key for a value of type [String]
我有一個序列化器方法,可以將我的swift對象轉換成字典,以便可以在http請求中發送它們。
這種特殊的方法是給我的問題
class func toDictionary ( _ order: Order ) -> Dictionary<String, Any> {
return [
"products" : NSArray(array:order.getProducts()),
"owning_user" : NSString(string: order.getOwningUser()),
"restaurant" : NSString(string: order.getRestaurantId())
]
}
order.getProducts()返回[String]類型的數組
當我在http請求中發送此消息時,它發送為
{"products[]":["...","..."],
"restaurant":"sdfsdf"
}
顯然,我的服務器期望產品作為關鍵,因此無法獲得正確的價值。
知道為什么要添加方括號嗎?
注意:
我的http請求是通過alamofire完成的
編輯:
原來問題出在alamofire
請參閱下面的解決方案
事實證明,當將字典作為httpBody傳遞時,這與alamofire的編碼有關。
對於有相同問題的任何人:
通過在您的Alamofire發布請求中添加以下屬性來解決此問題
encoing: JSONEncoding.default
最終的請求如下所示
Alamofire.request( requestURL, method: .post, parameters: orderJson, encoding: JSONEncoding.default)
並產生以下JSON被發布
{ restaurant: '580e33ee65b84973ffbc7beb',
products: [ '580f5cdafaa1067e55be696d' ],
owning_user: '580e2d174e93b0734e9a04cb'
}
正如我最初想要的。
好的,這似乎在這里起作用,所以我想我需要更多有關您的所作所為的上下文。 如果這可以解決您的問題,請投票! 謝謝! 可能的問題; 您可能在另一個數組中有一個數組? 如果order.getProducts()已經返回一個數組,請不要將其放在另一個數組中。 另一個選項可能是.flatMap它,“ NSArray(array:order.getProducts())。flatMap {$ 0}” <<將使數組中的單個數組成為數組。
//: Playground - noun: a place where people can play
import UIKit
func toDictionary () -> Dictionary<String, Any> {
return [
"products" : NSArray(array:["Paper","Pencil","Eraser"]),
"owning_user" : NSString(string: "user2976358"),
"restaurant" : NSString(string: "TacoBell")
]
}
let rValue = toDictionary()
let jsonData:Data!
do {
jsonData = try JSONSerialization.data(withJSONObject: rValue, options: .prettyPrinted)
let newString = String(data: jsonData, encoding: .utf8)
print(newString!)
} catch
{
print(error)
}
調試區域中的結果顯示了這一點
{
"restaurant" : "TacoBell",
"products" : [
"Paper",
"Pencil",
"Eraser"
],
"owning_user" : "user2976358"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.