我有一个像var arrayOfDictionary = [[:]]
这样的词典。现在我的tableviewcell中有一些数据,例如rate
,id
等。我在cellForRowAt
中将这些值存储在字典中......
var dictionary = ["id": "", "quantity": "","sellingPrice":""] as [String : Any]
dictionary["id"] = product?.id
dictionary["quantity"] = product?.quantity
dictionary["sellingPrice"] = product?.theRate
arrayOfDictionary.append(dictionary)
现在,当我打印arrayOfDictionary
时,我会得到类似的东西......
[[:], [AnyHashable("id"): "5", AnyHashable("sellingPrice"): "499", AnyHashable("quantity"): "-1"], [AnyHashable("id"): "8", AnyHashable("sellingPrice"): "500", AnyHashable("quantity"): "79"], [AnyHashable("id"): "8", AnyHashable("sellingPrice"): "500", AnyHashable("quantity"): "79"]]
即3个产品的id
,quantity
和rate
。但我不希望以这种格式使用此格式,而是想要第一组id
,rate
&一组quantity
,第二组id
,rate
& quantity
在另一组&等...... ..
简而言之,我希望他们采用这种格式...
[{"remaining_balance":"0.0","shipping_charges":0, "grand_total":320,"product_id”:”4”}, {"remaining_balance”:”1.0”,”shipping_charges”:200, "grand_total”:456,”product_id”:”5”}]
答案 0 :(得分:1)
首先,将您的字典明确声明为0.75000000000000055511151231257827021181583404541015625
,以便在打印时删除[String:Any]
。
其次,看起来您正在尝试获取JSON格式(在Swift中打印Dictionary时,您将获得方括号而不是卷曲的),要从字典数组中获取JSON,请使用{{ 1}}。
AnyHashable
您实际上不应该将JSON转换为String,我只是为了向您展示String格式,您可以使用JSONSerialization
类型的var arrayOfDictionary = [[String:Any]]()
var dictionary = ["id": "", "quantity": "","sellingPrice":""] as [String : Any]
dictionary["id"] = product?.id
dictionary["quantity"] = product?.quantity
dictionary["sellingPrice"] = product?.theRate
arrayOfDictionary.append(dictionary)
print(arrayOfDictionary) //[["id": "5", "sellingPrice": "-1", "quantity": "499"]]
do {
let jsonArrayOfDict = try JSONSerialization.data(withJSONObject: arrayOfDictionary)
print(String(data: jsonArrayOfDict, encoding: .utf8)!) //"[{\"id\":\"5\",\"sellingPrice\":\"-1\",\"quantity\":\"499\"}]"
} catch {
print(error)
}
变量来保存您的JSON数据或通过API将其上传到服务器。
答案 1 :(得分:0)
不要担心这也是一个字典数组,但你对JSON打印格式和字典打印格式数组感到困惑:
[[:], [AnyHashable("id"): "5", AnyHashable("sellingPrice"): "499", AnyHashable("quantity"): "-1"], [AnyHashable("id"): "8", AnyHashable("sellingPrice"): "500", AnyHashable("quantity"): "79"], [AnyHashable("id"): "8", AnyHashable("sellingPrice"): "500", AnyHashable("quantity"): "79"]]
这是你的数组中的字典:
[AnyHashable("id"): "5", AnyHashable("sellingPrice"): "499", AnyHashable("quantity"): "-1"],
您可以通过迭代来验证它:
for dict in arrayOfDictionary {
print(dict)
}
修改强>
var arrayOfDictionary = [[String:Any]]()
var dictionary = ["id": "", "quantity": "","sellingPrice":""] as [String : Any]
dictionary["id"] = product?.id
dictionary["quantity"] = product?.quantity
dictionary["sellingPrice"] = product?.theRate
arrayOfDictionary.append(dictionary)
let data = try! JSONSerialization.data(withJSONObject: arrayOfDictionary, options: .prettyPrinted)
print(data)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print(json)