我有一系列像这样的词典。
[["updated_at": , "expected_qty": 1, "parts_id": 1, "mappingType": service, "description": , "name": Epoxy, "created_at": , "price": 0, "win_service_id": 1, "id": 1, "mappingID": 1], ["updated_at": , "expected_qty": 1, "parts_id": 2, "mappingType": service, "description": , "name": Wood for Lami, "created_at": , "price": 0, "win_service_id": 1, "id": 2, "mappingID": 1]]
我需要将整个数组转换为转义字符串。这样的事情。
"[{\"updated_at\":\"\",\"expected_qty\":1,\"parts_id\":1,\"mappingType\":\"service\",\"description\":\"\",\"name\":\"Epoxy\",\"created_at\":\"\",\"price\":0,\"win_service_id\":1,\"id\":1,\"mappingID\":1},{\"updated_at\":\"\",\"expected_qty\":1,\"parts_id\":2,\"mappingType\":\"service\",\"description\":\"\",\"name\":\"Wood for Lami\",\"created_at\":\"\",\"price\":0,\"win_service_id\":1,\"id\":2,\"mappingID\":1}]"
我知道您可以使用array.description
将数组转换为字符串,但我不知道如何在其中转义这些字符。我搜索了很多,但我找不到这样做的方法。
我尝试添加字符串扩展来执行此类操作。
extension String {
var escaped: String {
return self.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
}
}
结果就是这样。
[[\"updated_at\": , \"expected_qty\": 1, \"parts_id\": 3, \"mappingType\": service, \"description\": , \"name\": Sill, \"created_at\": , \"price\": 0, \"win_service_id\": 8, \"id\": 3, \"mappingID\": 8]]
看起来它几乎是预期的输出,但注意内部方括号对。那些必须是大括号。
那么有更好的方法吗?
答案 0 :(得分:1)
您可以使用NSJSONSerialization将字典转换为json。请尝试以下代码
let dict = ["key":"value","key1":"0","key2":"1"] as Dictionary<String, AnyObject>
let data = try? NSJSONSerialization.dataWithJSONObject(dict, options:NSJSONWritingOptions.PrettyPrinted)
var datastring = String(data: data!, encoding: NSUTF8StringEncoding)