-1
我有字典數組[[String:Any]]我想將其轉換爲JSON字符串。但我不知道如何開始。我試過JSONSerialization.data(withJSONObject:array,options:.prettyPrinted),並將數組傳遞給方法,但它顯示錯誤。任何解決方案請在下面評論謝謝。將Swift 3數組轉換爲JSON
我有字典數組[[String:Any]]我想將其轉換爲JSON字符串。但我不知道如何開始。我試過JSONSerialization.data(withJSONObject:array,options:.prettyPrinted),並將數組傳遞給方法,但它顯示錯誤。任何解決方案請在下面評論謝謝。將Swift 3數組轉換爲JSON
嘗試如下的代碼...
do {
//Convert to Data
let jsonData = try JSONSerialization.data(withJSONObject: dictionaryArray, options: JSONSerialization.WritingOptions.prettyPrinted)
//Do this for print data only otherwise skip
if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
print(JSONString)
}
//In production, you usually want to try and cast as the root data structure. Here we are casting as a dictionary. If the root object is an array cast as [AnyObject].
var json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: AnyObject]
} catch {
print(error.description)
}
您可以包括你的代碼? –
如果這是一個Swift問題,請添加相關標籤。此外,您應該提供您嘗試顯示的具體錯誤。 –
[在swift中將數組轉換爲JSON字符串]的可能重複(http://stackoverflow.com/questions/28325268/convert-array-to-json-string-in-swift) –