È possibile utilizzare il seguente codice:
var error: NSError?
var dict: NSDictionary = [
"1": 1,
"2": "Two",
"3": false
]
let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: &error)
if let data = data {
let json = NSString(data: data, encoding: NSUTF8StringEncoding)
if let json = json {
println(json)
}
}
Dato un NSDictionary
, esso viene serializzato come NSData
, quindi convertito in NSString
.
Il codice facendo la conversione può anche essere riscritta in modo più conciso come:
Swift 3:
do {
let jsonData = try JSONSerialization.data(withJSONObject: data)
if let json = String(data: data, encoding: .utf8) {
print(json)
}
} catch {
print("something went wrong with parsing json")
}
risposta originale:
if let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if let json = NSString(data: data, encoding: NSUTF8StringEncoding) {
println(json)
}
}
Nota che, per la serializzazione per il lavoro del dizionario deve contenere chiavi e valori JSON validi.
La tua domanda ha avuto una risposta: http://stackoverflow.com/questions/6368867/generate-json-string-from-nsdictionary –
voglio convertire NSDictionary Json in NSstring usando Swift – Gayathri
puoi aiutarci? – Gayathri