xxxxxxxxxx
// for encoing your model or sturct must inherit codable protocol
var general = [str: products]
let encodedData = try? JSONEncoder().encode(general)
xxxxxxxxxx
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)
}
}
xxxxxxxxxx
extension String {
func toJSON() -> Any? {
guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
}
}
xxxxxxxxxx
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)
}
}