convertir datos a json swift
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
}catch{ print("erroMsg") }
Dead Dormouse
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
}catch{ print("erroMsg") }
let jsonText = "{\"first_name\":\"Sergey\"}"
var dictonary:NSDictionary?
if let data = jsonText.data(using: String.Encoding.utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" First name is: \(myDictionary["first_name"]!)")
}
} catch let error as NSError {
print(error)
}
}
func jsonToString(json: AnyObject){
do {
let data1 = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted) // first of all convert json to the data
let convertedString = String(data: data1, encoding: NSUTF8StringEncoding) // the data will be converted to the string
print(convertedString) // <-- here is ur string
} catch let myJSONError {
print(myJSONError)
}
}