2016-09-29 24 views
0

在我swift iOS應用我有一個[字符串]數組,我想建立一個基於它的字符串有什麼正確使用joinWithSeparator在斯威夫特在我的代碼有:當我想用「

var processedString: String = "" 

processedString = "\(hashtags.joinWithSeparator("\", \""))" 

然後我alamofire把它上傳到我的服務器

目前我的服務器上它創建MongoDB中的條目:

"hashtags" : [ "test\", \"one\", \"two" ], 

我想擺脫\標記並僅保留"。我試圖做的:

processedString = "\(hashtags.joinWithSeparator(", "))" 

但後來我的服務器上,我有:

"hashtags" : [ "test, one, two" ], 

,我需要它作爲一個字符串數組:

"hashtags" : [ "test", "one", "two" ], 

我在做什麼錯在這裏?

+2

你會對此完全錯誤的。不要手動構建字符串的JSON輸出。改用'JSONSerialization'。 – rmaddy

+0

maddy你能給我舉個例子嗎? – user3766930

+1

請搜索。有無數的例子將字典/數組轉換爲JSON。 – rmaddy

回答

0

由於一系列原因,您不能使用hashtags.joinWithSeparator(),而不是在數組值之間插入分隔符,而不是在它們之前和之後。

而是使用這個斯威夫特3示例代碼:

let hashtags = ["test", "one", "two"] 
let data = try JSONSerialization.data(withJSONObject: hashtags, options: []) 
let processedString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) 

(我離開了很多子彈打樣爲清楚起見的。)