我需要在{}中对Dictionary进行回复,但是他们以[]形式给出。请帮忙。这是我的代码
func getRequestObject() -> Dictionary<String,AnyObject> {
var requestObject = Dictionary<String,AnyObject>()
requestObject["username"] = "a"
requestObject["password"] = "a"
return requestObject
}
他们给我回复
["password": a, "username": a]
但我需要回复
{"password": a, "username": a}
答案 0 :(得分:1)
你必须像这样将你的词典转换为json formate:
do
{
let jsonData = try NSJSONSerialization.dataWithJSONObject(someDict, options: NSJSONWritingOptions(rawValue:0))
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
print(jsonString)
}
catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
答案 1 :(得分:1)
检查一下:
if let jsonData = try? NSJSONSerialization.dataWithJSONObject(getRequestObject(), options: [])
{
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
print(jsonString)
}
输出
{"password": "a", "username": "a"}
&#34; a&#34;是因为类型是字符串。如果您不需要报价,请尝试另一种快速替代方法,如下所示:
var myString = getRequestObject().description
let myRange = myString.startIndex..<myString.startIndex.advancedBy(1)
myString.replaceRange(myRange, with: "{")
let myRange2 = myString.endIndex.advancedBy(-1)..<myString.endIndex
myString.replaceRange(myRange2, with: "}")
print(myString)
答案 2 :(得分:1)
Swift标准库中的字典具有以下语法:
let dict = [key : value, key : value, ...]
// in your case probably
let dict = getRequestObject()
打印或将其转换为String
会产生相同的格式:[...]
对于带花括号的格式,您可以将字典强制转换为NSDictionary
let dict2 = dict as NSDictionary
// both result in "{key : value, key : value, ...}"
String(dict2)
print(dict2)
答案 3 :(得分:-2)
您希望字典description
使用{}
代替[]
吗?这很简单,只需要一些字符串操作即可完成工作!
我们需要将字符串的第一个和最后一个char设置为“{”和“}”。那么让我们写一个setChar
函数:
func setChar (at index: Int, _ str: String, to ch: Character) -> String {
var charArr = Array(str.characters)
charArr[index] = ch
var finalString = ""
for c in charArr {
finalString += String(c)
}
return finalString
}
我只是将字符拆分成一个数组,设置字符,然后再将它们连接在一起并返回。
现在你可以先得到字典的描述:
var description = getRequestObject().description
然后调用函数:
description = setChar(at: 0, description, to: "{")
description = setChar(at: description.characters.count - 1, description, to: "}")
和BOOM!你会看到预期的结果!
您甚至可以将setChar
功能扩展为String
!
extension String {
func setChar (at index: Int, to ch: Character) -> String {
var charArr = Array(self.characters)
charArr[index] = ch
var finalString = ""
for c in charArr {
finalString += String(c)
}
return finalString
}
}