Here is the code for the below Json output:
let params : [[String : AnyObject]] = [[\"name\" : \"action\", \"value\" : \"pay\" ],[\"name\" : \"cartJsonData\
Try this.
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)
}
}
Xcode 11, converted String to NSString is working for me.
func jsonToString(json: AnyObject) -> String{
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data1, encoding: String.Encoding.utf8) as NSString? ?? ""
debugPrint(convertedString)
return convertedString as String
} catch let myJSONError {
debugPrint(myJSONError)
return ""
}
}
Using the new Encodable based API, you can get the string version of a JSON file using String(init:encoding) initialiser. I ran this in a Playground and the last print statement gave me
json {"year":1961,"month":4}
It seems that the format uses the minimum number of characters by detail.
struct Dob: Codable {
let year: Int
let month: Int
}
let dob = Dob(year: 1961, month: 4)
print("dob", dob)
if let dobdata = try? JSONEncoder().encode(dob) {
print("dobdata base64", dobdata.base64EncodedString())
if let ddob = try? JSONDecoder().decode(Dob.self, from: dobdata) {
print("resetored dob", ddob)
}
if let json = String(data: dobdata, encoding: .utf8) {
print("json", json)
}
}
if you are using Swifty JSON
var stringfyJSOn = yourJSON.description
For Reference or more information
https://github.com/SwiftyJSON/SwiftyJSON
Swift 4.0
static func stringify(json: Any, prettyPrinted: Bool = false) -> String {
var options: JSONSerialization.WritingOptions = []
if prettyPrinted {
options = JSONSerialization.WritingOptions.prettyPrinted
}
do {
let data = try JSONSerialization.data(withJSONObject: json, options: options)
if let string = String(data: data, encoding: String.Encoding.utf8) {
return string
}
} catch {
print(error)
}
return ""
}
Usage
stringify(json: ["message": "Hello."])
Swift (as of December 3, 2020)
func jsonToString(json: AnyObject){
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
print(convertedString ?? "defaultvalue")
} catch let myJSONError {
print(myJSONError)
}
}