2016-04-08 8 views
8

So che c'è una domanda con lo stesso titolo here. Ma in quella domanda, sta provando a convertire un dizionario in JSON. Ma ho una semplice puntura come questa: "giardino"Convertire una stringa semplice in JSON String in swift

E devo spedirlo come JSON. Ho provato SwiftyJSON ma ancora non riesco a convertirlo in JSON.

Ecco il mio codice:

miei crash codice alla ultima riga:

fatal error: unexpectedly found nil while unwrapping an Optional value 

sto facendo qualcosa di sbagliato?

risposta

18

JSON has to be an array or a dictionary, non può essere solo una stringa.

Vi suggerisco di creare un array con il tuo stringa in esso:

let array = ["garden"] 

quindi si crea un oggetto JSON da questa matrice:

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

Se avete bisogno di questo JSON come una stringa invece di i dati è possibile utilizzare questo:

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

Stampe:

[ "giardino"]

Se si preferisce avere un dizionario piuttosto che un array, seguire la stessa idea: creare il dizionario quindi convertirlo.

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

Stampe:

{ "location": "giardino"}

1

Swift 3 Versione:

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