I have this Object [Dictionary< String: Any>]
[{
"addCity" : "Xyz",
"addLandmark" : "Shopper",
"addCountry" : "Abc",
"addPincode" : "122001",
"isPrimary" : "false",
"addAddress" : "S44",
"addState" : "abc",
"addAddress2" : "Grand Road",
"addContact" : "11111111",
"addName" : "John"
}]
and want to convert this into this:
"{\"addAddress\":\"S44\",\"addAddress2\":\"Grand Road\",\"addCity\":\"Xyz\",\"addContact\":\"11111111\",\"addCountry\":\"abc\",\"addLandmark\":\"Shopper\",\"addName\":\" John\",\"addPincode\":\"122002\",\"addState\":\"abc\",\"isPrimary\":true}"
means I have to stringify the above values and tried various methods but not reached to any solution.
I have tried this
do {
let arrJson = try JSONSerialization.data(withJSONObject: dataAddress, options: JSONSerialization.WritingOptions.prettyPrinted)
let string = String(data: arrJson, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
let tempJson = string! as String
print("%%%%%%",tempJson)
}catch let error as NSError{
print(error.description)
}
but it just retruned the same in JSON form.
Please can any help me.
This may do the trick, but you can fiddle around with it as you like (Swift 3):
typealias JSONDictionary = [String : Any]
func asString(jsonDictionary: JSONDictionary) -> String {
do {
let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: .prettyPrinted)
return String(data: data, encoding: String.Encoding.utf8) ?? ""
} catch {
return ""
}
}
let dict: JSONDictionary = ["foo": 1, "bar": 2, "baz": 3]
let dictAsString = asString(jsonDictionary: dict)
// prints "{\n "bar" : 2,\n "baz" : 3,\n "foo" : 1\n}"
Here is a safe/communicative extension:
extension Dictionary where Key == String, Value == Any {
var stringified: String? {
do {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
guard let stringy = String(data: data, encoding: .utf8) else {
print("ERROR: failed to cast data as string")
return nil
}
return stringy
} catch let err {
print("error with " + #function + ": " + err.localizedDescription)
return nil
}
}
}
Here is an alternative that may save you time for encodable objects.
extension Encodable
var stringified: String? {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self) else { return nil }
return String(data: data, encoding: .utf8)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With