2017-01-04 7 views
-1

辞書の配列[[String:Any]]をJSON文字列に変換したいです。しかし、私はどのようにそれを開始するのか分からない。 JSONSerialization.data(withJSONObject:array、options:.prettyPrinted)を試してみましたが、メソッドに配列を渡しましたが、エラーが表示されます。どんな解決策も下記にコメントしてください。感謝。Swift 3 ArrayをJSONに変換する

+0

は、あなたのコードを含めてもらえますか? –

+0

これは迅速な質問の場合は、関連するタグを追加してください。また、試行中に表示される特定のエラーを提供する必要があります。 –

+0

[配列をすぐに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) 
    }