7

I have an Object of type [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 returned the same in JSON form.

Please can anyone help me.

Deitsch
  • 1,610
  • 14
  • 28
Aditya
  • 783
  • 1
  • 8
  • 25
  • What object is this ? Looks like you have just a data (JSON String). If you just want to print the data returned from your API `String(data: data, encoding: .utf8)` – Leo Dabus Jan 31 '17 at 20:44
  • 2
    this is not a valid Swift Array of Dictionary – Leo Dabus Jan 31 '17 at 20:48
  • That'd be an array of dictionaries. Try getting one of the items them do the conversion. – pinedax Jan 31 '17 at 20:48
  • I am making this object from my side and have to send this object in stringify form to server. – Aditya Jan 31 '17 at 20:49
  • Just do the opposite JSONSerialization data(withJSONObject: – Leo Dabus Jan 31 '17 at 20:50
  • @LeoDabus i have tried NSJSONSerialization and have casted [[String: Any]] but it has returned me the same in JSON form – Aditya Jan 31 '17 at 20:51
  • to POST you need to declare a native Swift array `[[String: Any]]`, initialize it with your info and convert the array to data using `JSONSerialization data(withJSONObject:` – Leo Dabus Jan 31 '17 at 20:53
  • Swift native type is String not NSString. – Leo Dabus Jan 31 '17 at 20:56
  • 1
    Why would you need the String instead of the JSON Data to post ? – Leo Dabus Jan 31 '17 at 20:56
  • I have to pass this string data to a value in Json data to post ..... I changed NSString to String but the output was same – Aditya Jan 31 '17 at 21:02
  • You're confused. JSON *string* representation is for humans, so that they can read it. Computers don't give a damn, they want *data*. Your server needs JSON data, not a JSON string. – Eric Aya Feb 01 '17 at 10:04

2 Answers2

9

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}"
BJ Miller
  • 1,536
  • 12
  • 16
3

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)
    }
}
Deitsch
  • 1,610
  • 14
  • 28
ScottyBlades
  • 12,189
  • 5
  • 77
  • 85