Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringify dictionary in Swift

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.

like image 558
Aditya Avatar asked Jan 31 '17 20:01

Aditya


2 Answers

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}"
like image 119
BJ Miller Avatar answered Jan 04 '23 01:01

BJ Miller


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)
    }
}
like image 38
ScottyBlades Avatar answered Jan 04 '23 02:01

ScottyBlades