【发布时间】:2016-01-28 17:56:34
【问题描述】:
我有一系列像这样的字典。
[["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]]
看起来几乎是预期的输出,但请注意内部的方括号对。那些必须是大括号。
那么有没有更好的方法来做到这一点?
【问题讨论】:
-
建议:您可能希望改为从字典创建 JSON。喜欢stackoverflow.com/a/29625483/2227743(如果我猜对了你在这里做什么)
-
你想要这个特殊的字符串格式做什么?
-
@EricD。我会试试这个。谢谢。
-
@caseynolan 这是一个 HTTP POST 正文。这个奇怪的 API 需要一个 JSON 字典数组作为字符串。
标签: ios arrays string swift escaping