2017-01-04 146 views
-1

我有字典数组[[String:Any]]我想将其转换为JSON字符串。但我不知道如何开始。我试过JSONSerialization.data(withJSONObject:array,options:.prettyPrinted),并将数组传递给方法,但它显示错误。任何解决方案请在下面评论谢谢。将Swift 3数组转换为JSON

+0

您可以包括你的代码? –

+0

如果这是一个Swift问题,请添加相关标签。此外,您应该提供您尝试显示的具体错误。 –

+0

[在swift中将数组转换为JSON字符串]的可能重复(http://stackoverflow.com/questions/28325268/convert-array-to-json-string-in-swift) –

回答

0

尝试如下的代码...

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) 
    }