2016-04-08 16 views
8

同じタイトルの質問があることを知っていますhere。しかし、その質問では、辞書をJSONに変換しようとしています。しかし、私はこのような簡単な刺青を持っています: "garden"簡単な文字列をJSON Stringに変換する

そして私はJSONとしてそれを送る必要があります。 SwiftyJSONを試しましたが、これをJSONに変換できません。ここで

が私のコードです:

最後の行で、私のコードがクラッシュ:

fatal error: unexpectedly found nil while unwrapping an Optional value 

は私が何か間違ったことをやっていますか?

答えて

18

JSON has to be an array or a dictionaryは、文字列だけではありません。

私はあなたがそれであなたの文字列の配列を作成してお勧め:

let array = ["garden"] 

次にあなたがこの配列からJSONオブジェクトを作成します。

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
    // here `json` is your JSON data 
} 

を文字列として、このJSONが必要な場合は代わりに

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
    // here `json` is your JSON data, an array containing the String 
    // if you need a JSON string instead of data, then do this: 
    if let content = String(data: json, encoding: NSUTF8StringEncoding) { 
     // here `content` is the JSON data decoded as a String 
     print(content) 
    } 
} 

プリント:

データあなたはこれを使用することができますそれを変換し、その後辞書を作成する:あなたは辞書ではなく、アレイを有することを好む場合は3210

[「庭」]

、同じ考えに従ってください。

let dict = ["location": "garden"] 

if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) { 
    if let content = String(data: json, encoding: NSUTF8StringEncoding) { 
     // here `content` is the JSON dictionary containing the String 
     print(content) 
    } 
} 

プリント:

{ "場所": "庭園"}

1

スウィフト3版:

let location = ["location"] 
    if let json = try? JSONSerialization.data(withJSONObject: location, options: []) { 
     if let content = String(data: json, encoding: .utf8) { 
      print(content) 
     } 
    } 
関連する問題